简体   繁体   English

通过基类方法访问属性

[英]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. 方法logs:add在第三个参数上收到NULL。 I wish to have 'Users'. 我希望有“用户”。

What i'm doing wrong? 我做错了什么? Additionally. 另外。 How to avoid notice in base class method? 如何避免基类方法中的通知?

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;
}

Replace self keyword with static keyword in your code and it will work. 在代码中将self关键字替换为static关键字,它将起作用。

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. 通过在代码中使用self,实际上是在引用未初始化的CoreModule类中定义的属性$ info。 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. 并且即使您在派生类中重写$ info,由于早期绑定到父类,所以未引用此重写属性。

static keyword references that version of the property which is defined in the class from which it is called. static关键字引用在调用它的类中定义的该属性的版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM