了解PHP语言中的范围解析运算符的定义

问题描述 投票:-1回答:1

在php手册上,它们如下定义作用域解析运算符:

[范围解析运算符(也称为Paamayim Nekudotayim),或更简单的说,是双冒号,是一种令牌,它允许访问静态,常量和重写的属性或类的方法。

我的理解是,因为我们无法使用$this评估静态属性,类常量和静态方法,所以我们需要::。我不明白为什么允许::从类内部评估非静态函数。可以说,子类可能想使用parent::baseClassMethod()评估父类中定义的方法,但随后它可能也想评估父类中定义的属性,但是::无法评估属性。可以说父类的属性是继承的,因此我们可以简单地用$this->prop来评估它们,但是方法也是如此。仅在子类中重写方法时,才将::用于方法。同样,我们需要::来评估子类中的重写属性。与php手册定义相反,如果尝试使用::评估覆盖的属性,则会引发错误。

为了说明我的观点,我有以下示例PHP代码:

error_reporting(E_ALL);
class myClass {
    private $prop = 786; 
    public $prop2 = 123;

    public function changeType($var, $type){
        settype($var, $type);
        echo "function assessed through self";
    }
    public function display_prop(){
        self::changeType(1, "string"); //why does this not throw error for non static function?
        var_dump(self::$prop); //throws error; can't assess properties with self as expected.
    }    
}

class childCLass extends myClass {
    public $prop2 = "new"; //overriden property.

    public function display_prop(){ //overriden method.
        echo "I do different things from the base class". "</br>";      
    }
    public function dsiplay_overriden(){
        echo parent::$prop2; //Why can't assess overriden properties, as suggested in the definition?
    }
}

$obj = new myClass;
$obj->display_prop(); 

$obj2 = new childCLass;
$obj2->display_prop();
$obj2->dsiplay_overriden();

childClass::display_prop(); //This throws error as expected because non-static method.

总结起来,我主要有两个具体问题:

  1. 为什么我们不能使用定义中定义的::访问覆盖的属性?
  2. 为什么与定义相反,为什么我们可以在带有::的类中访问非静态函数?

P.S:已对stackoverflow询问similar question。目前还没有令人满意的答案,而且我正在寻找一种概念性且有见地的答案,它更适合程序员。stackexchange。

php inheritance static static-methods scope-resolution-operator
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.