能够使用箭头运算符->?通过对象访问静态属性。

时间:2018-06-27 06:04:40

标签: php oop

我已经读过Static properties cannot be accessed through the object using the arrow operator ->.,可以使用解析运算符通过类名称访问静态属性。

在下面的示例中,我可以使用arrow operator ->通过对象访问静态方法。

class Foo {
   public static $name="I am php";
    public static function aStaticMethod() {
        // ...
        echo 'In Static method';
    }
}

Foo::aStaticMethod();//output: In Static method    
$obj = new Foo;   
$obj->aStaticMethod();//output: In Static method
$obj->name;

输出:

In Static methodIn Static method

但是当尝试通过operator ->访问变量$ name时,会出现以下错误:

PHP Notice:  Accessing static property Foo::$name as non static in /home/jdoodle.php on line 14
PHP Notice:  Undefined property: Foo::$name in /home/jdoodle.php on line 14

php确实确实支持OOP吗?Static properties cannot be accessed through the object using the arrow operator ->是什么意思?

谢谢

2 个答案:

答案 0 :(得分:2)

问题是由于对属性a property is a variable defined in a class的误解造成的。如果您在上方展开示例并添加属性...

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

class Foo {
    public static $a = "static property";

    public static function aStaticMethod() {
        // ...
        echo 'In Static method';
    }
}

Foo::aStaticMethod();//output: In Static method
echo Foo::$a;
$obj = new Foo;
$obj->aStaticMethod();//output: In Static method
echo $obj->a;

这会尝试引用$a,但输出是...

In Static methodstatic propertyIn Static methodPHP Notice:  Accessing static property Foo::$a as non static in /home/nigel/workspace2/Test/t2.php on line 18
PHP Stack trace:
PHP   1. {main}() /home/nigel/workspace2/Test/t2.php:0
PHP Notice:  Undefined property: Foo::$a in /home/nigel/workspace2/Test/t2.php on line 18
PHP Stack trace:
PHP   1. {main}() /home/nigel/workspace2/Test/t2.php:0

Notice: Accessing static property Foo::$a as non-static in /home/nigel/workspace2/Test/t2.php on line 18

Call Stack:
    0.0001     348024   1. {main}() /home/nigel/workspace2/Test/t2.php:0


Notice: Undefined property: Foo::$a in /home/nigel/workspace2/Test/t2.php on line 18

Call Stack:
    0.0001     348024   1. {main}() /home/nigel/workspace2/Test/t2.php:0

(请注意,我已将其设置为报告所有错误/警告等。)

答案 1 :(得分:-1)

根据PHP文档:

“将类属性或方法声明为静态,可以在不需要实例化类的情况下对其进行访问。被实例化为类的对象无法访问声明为静态的属性(尽管静态方法可以)。”

Example from PHP doc