考虑下面的代码:冲突的非静态的静态瓦尔改变值
class A {
private $a;
function f() {
A::a = 0; //error
$this->a = 0; //error
$self::a = 0; //error
}
}
我怎样才能改变F中$a
()?
考虑下面的代码:冲突的非静态的静态瓦尔改变值
class A {
private $a;
function f() {
A::a = 0; //error
$this->a = 0; //error
$self::a = 0; //error
}
}
我怎样才能改变F中$a
()?
你接近。或者:
self::$a = 0; //or
A::$a = 0;
如果它是静态的,或者:
$this->a = 0;
如果它不是。
显然我们都被问题的标题所欺骗,尽管这里是你如何改变$ 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();
?>
输出:
一个:10如果你想美元是静态的使用以下
:
<?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
?>
那不是只能是如果'$ a'被声明为'static'?我不明白为什么'$ this-> a = 0;'在上面的代码中不起作用,除非他静态地调用f()'... – DaveRandom
+1来修复这两个问题! –
@DaveRandom,因为在这种情况下,$ a是一个静态成员,而一个静态成员不属于该对象,$ this返回对象引用。 –