tomfl
tomfl

Reputation: 707

Calling protected properties without using $this->

I am reading a book about creating a MVC Framework in PHP. In the second chapter, we build a class that is a bit strange. Let me explain with an example.

The class is called Inspector. Here are the properties :

protected $_class;
protected $_properties = array();
protected $_methods = array();

protected $_meta = array(
            "class" => array(),
            "properties" => array(),
            "methods" => array()
    );

So as you can see, they are all declared protected.

But now, here is one of the many methods of the class :

public function getClassMethods()
{
    if (!isset($_methods))
    {
        $methods = $this->_getClassMethods();
        foreach ($methods as $method)
        {
            $_methods[] = $method->getName();
        }
    }
    return $_properties;
}

_getClassMethods() is a method that was declared a few lines above, but it is not important for our example.

So apparently, $_methods is the property declared previously. But why is it that it is not preceded by $this-> ? First, I thought it is because the property is declared as protected, but I did some tests to see if it was normal and working, but of course it threw an error.

I can't believe the error comes from the book : the writers are professional PHP developers, I think, and they did the same mistake (?) in pretty much all of the other methods declared in the class.

So, is it possible for PHP to call a property without using $this-> ? Does it have to do with a configuration line in php.ini (or something like that) ? Maybe it is because it's an old version of PHP that is used.

Upvotes: 3

Views: 49

Answers (1)

gen_Eric
gen_Eric

Reputation: 227220

Inside your function, $_methods and $this->_methods would be two different variables/properties.

To access the protected $_methods property you need to use $this->_methods. This is available in any method of the class.

If you just use $_methods, then you are creating/accessing a variable that will only exist inside that method and will go away when the method is finished executing.

Therefore, the book is incorrect and in your method you need to use $this->_methods and $this->_properties.

Upvotes: 3

Related Questions