Neevor
Neevor

Reputation: 1

Access to property by base class method

Base class:

   class CoreModule {
    private static $info;

    public static function getModuleInfo($key=null){
        //Notice: Undefined index: name
        if($key) return self::$info[$key];
        else return self::$info;
    }

    public static function getModuleName(){
        return self::getModuleInfo('name');
    }

Derived class:

final class users extends CoreModule {
    public static $info = Array(
        'name' => 'Users',
        'version' => '2.0',
        'access' => 999,
        'icon' => 'img/user_gray.png'
    );
    ...
    ...
    logs::add(1, 'logged', self::getModuleName());

Method logs:add receives NULL on 3rd argument. I wish to have 'Users'.

What i'm doing wrong? Additionally. How to avoid notice in base class method?

Upvotes: 1

Views: 75

Answers (2)

Jibran Bhat
Jibran Bhat

Reputation: 97

Replace self keyword with static keyword in your code and it will work.

You need to use late static bindings. By using self in your code, you are essentially referencing the property $info defined in the CoreModule class which isn't initialized. And even though you are overriding $info in the derivied class, this overridden property isn't referenced because of early binding to the parent class.

static keyword references that version of the property which is defined in the class from which it is called.

Upvotes: 1

Scopey
Scopey

Reputation: 6319

You should be using "Late static bindings"

Try this:

public static function getModuleInfo($key=null)
{
    if($key) return static::$info[$key];
    else return static::$info;
}

Upvotes: 1

Related Questions