在php对象中,为什么静态变量只能用:: notation访问,但静态方法可以从::& - >调用

In PHP, for e.g. you define a variable & method static in a class. For its objects, why we can only access variables with :: notation while we can run static methods with -> or :: both? Why this dual behaviour?

class first {
    //variable
    public static $var=5;

    //method
    static function new(){
        echo "<br>";
        echo self::$var;
        echo "<br>";
    }
}

class second {

}

$obj = new first();

echo $obj->$var; // this throws an error
echo $obj::$var; // this runs
$obj->new(); // this also runs
$obj::new(); // this runs
duanjue6575
duanjue6575 所以你的意思是说它是如何设计oop或它只是PHP?编译或解释语言有什么意义?
大约一年之前 回复
douye9175
douye9175 正如它的写作,它听起来基于意见。除了“它是如何设计的”之外,无法回答。如果你要详细说明你的困惑,有人可以解释PHP不是一种编译语言。
大约一年之前 回复
douyou7878
douyou7878 我想知道这个问题有什么问题吗?对这个问题的评价很低。
大约一年之前 回复

1个回答

Although arbitrary, a static class variable only belongs to a class, not to an object. A static class method belongs to both a class and an object of that class.

As demonstrated below, changing a static variable of a class would change the variable in all instances of that class. So the -> notation would be deceitful. This does not happen with a static class method.

Imagine that -> would be allowed on static variables, then

calling $someObjectOfTypeX->some_static_variable = 'some_value' would change the state of $anotherObjectOfTypeX.

Calling $someObjectOfTypeX->someStaticFunction() however, does not change the state of $anotherObjectOfTypeX.

Although the keyword static is identical it has different implications for functions and variables. Static variables are shared by all instances of a class. Static function don't alter the objects state and therefore also will not change the state of other instances of the same class.

<?php

class first
{
    //variable
    public static $var = 5;

    //method
    static function new()
    {
        echo "<br>";
        echo self::$var;
        echo "<br>";
    }
}

$obj1 = new first();
$obj2 = new first();

echo $obj1->var; // this throws an error
echo $obj1::$var; // this runs
echo first::$var; // this runs

$obj2::$var = 10; // changes $var in class first (both object $obj1 and object $obj2)
$obj2->var = 15; // this throws an error (if it didn't it would change the variable also in $obj1)

$obj1->new(); // this also runs
$obj1::new(); // this runs
first::new(); // this runs
dtsc1684
dtsc1684 我已经扩展了我的答案,并解释了static关键字对变量和方法有不同的含义。
大约一年之前 回复
donglan7594
donglan7594 你说虽然是任意的,但静态类变量只属于一个类,而不属于一个对象。 静态类方法既属于该类的类,也属于该类的对象。 但static是一个关键字,我们可以在该关键字的所有实例中共享一些属性或方法。 这适用于属性和方法,即它们都属于类和方法。 但我在这里问的是,为什么我们可以使用 - >&::访问方法,而在属性的情况下只能使用::来访问它。
大约一年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问