Jump to content

need help with exercise


benom

Recommended Posts

Hello everyone,

I just got a task on my University but I'm not sure if I understend it correctly.

I need to find one mistake in this code:

 

 

class number
{
    public $_a = 3;
    public function __construct()
    {
    $this->_a = 4;
    }
    public static function out()
    {
    echo self::$_a * 5;
    }
}
number::out()

 

I guess the answer will be 15 after I will change public $_a = 3; to static $_a = 3;. It shows number but im not sure if im correct :)

Link to comment
Share on other sites

I was getting an error like this one:

Fatal error: Access to undeclared static property: number::$_a

So I guess it was problem with making _a visible outside of class. Thats why I changed it.

Edited by benom
Link to comment
Share on other sites

No, this has nothing to do with visibility. Those are all public attributes, and you don't even try to access them outside of the class.

 

The problem is the static modifier. You've found that already, but you somehow didn't draw the right conclusions. A static method belongs to the class itself. A non-static attribute, on the other hand, is associated with a particular instance of the class. That code is trying to mix the two levels: It calls a static method, but then it tries to access a non-static attribute within the method. This is invalid and simply makes no sense. The class simply doesn't have a $_value attribute (but its instances have).

Edited by Jacques1
Link to comment
Share on other sites

To boil this down for you, you need to understand the difference between self and this, and when to use those, as well as how static methods work, and when those are appropriate (or not) to use in a class.

 

The original code has a couple of different implications.

 

For example the constructor is setting the initial value of the $_a class variable.  Is that important for the class to retain?  If so, it doesn't make sense to me that you would have a static class variable, which it doesn't at present.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.