-5

enter image description here

enter image description here

enter image description here

I'm new in OOP with PHP and I'm wondering why I can't declare an instance variable in my class so that I can use it properly. If declaring the variable like on the picture at the top, I get the error message from picture 3. If I add the "public" modifier to the variable, my PHP file says exactly nothing (No Error, just a white empty screen). It all works when I write the string directly into my function, but I wanted to try out using an instance variable.

I tried to solve this problem by myself and didn't find any solutions. So please don't be too mad about it.

smac89
  • 39,374
  • 15
  • 132
  • 179
  • 2
    Welcome to StackOverflow! Please read [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask) and post the code on your question. – Pedro Lobito May 09 '16 at 19:54
  • Declare an access specifier(*public*, *private* or *protected*) for your instance variable `$name`. And in your `returnName()` method, instead of `return $name` do `return $this->name;` to return the instance property. – Rajdeep Paul May 09 '16 at 20:02

1 Answers1

0

Your return $name; searches for a variable $test in your function/method scope. To access the class property, you have to specify it:

class recipeapi
{
    // add visibility keyword here
    private $name = 'Felix';

    // kind of standard is to use get...(), but return...() works the same way
    public function getName()
    {
        // use $this->varname if you want to access a class property
        return $this->name;
    }
}
clemens321
  • 2,103
  • 12
  • 18
  • Thanks, for your answer :). I'll try it out as soon as i get home. – CheNativara May 10 '16 at 12:53
  • I did the whole thing now and it worked. I have one more question. Do i have to call the variable over $this->name without the $ before the name because it wouldnt fit in the syntax? – CheNativara May 10 '16 at 16:11
  • Yes, the $ in front of "this" counts ;-) It's actually the first example here: http://php.net/manual/de/language.oop5.basic.php – clemens321 May 10 '16 at 16:29