在更改值时,静态变量与非静态变量发生冲突

时间:2012-05-04 15:18:32

标签: php

请考虑以下代码:

class A {
    private $a;

    function f() {
        A::a = 0; //error
        $this->a = 0; //error
        $self::a = 0; //error
    }
}

如何更改f()中的$a

3 个答案:

答案 0 :(得分:2)

你很亲密。之一:

self::$a = 0; //or
A::$a = 0;

如果它是静态的,或者:

$this->a = 0;

如果不是。

答案 1 :(得分:1)

我相信语法是:

self::$a

答案 2 :(得分:1)

显然,我们都被问题的标题所欺骗,不过这是你如何改变$ a的价值。

<?php

class A {
    private $a;

    function f() {
        //A::a = 0; //error
        $this->a = 10; //ok
        //$self::a = 0; //error
    }

    function display() {
        echo 'a : ' . $this->a . '<br>';
    }
}

$a = new A();
$a->f();
$a->display();

?>

输出:

a:10 如果你想要$ a是静态的,请使用以下内容:

<?php

class A {
    private static $a;

    function f() {
        //A::$a = 0; //ok
        //$this->a = 10; //Strict Standards warning: conflicting the $a with the static $a property
        self::$a = 0; //ok
    }

    function display() {
        echo 'a : ' . self::$a . '<br>';
    }
}

$a = new A();
$a->f();
$a->display();
// notice that you can't use A::$a = 10; here since $a is private

?>
相关问题