0

考虑以下代码:

class A {
    private $a;

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

如何更改$af()?

4

3 回答 3

2

你很亲密。任何一个:

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

如果它是静态的,或者:

$this->a = 0;

如果不是。

于 2012-05-04T15:20:08.273 回答
1

我相信语法是:

self::$a
于 2012-05-04T15:20:01.653 回答
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

?>
于 2012-05-04T15:29:07.297 回答