次のコードを検討してください。
class A {
private $a;
function f() {
A::a = 0; //error
$this->a = 0; //error
$self::a = 0; //error
}
}
$a
f() で変更するにはどうすればよいですか?
次のコードを検討してください。
class A {
private $a;
function f() {
A::a = 0; //error
$this->a = 0; //error
$self::a = 0; //error
}
}
$a
f() で変更するにはどうすればよいですか?
あなたは近かった。また:
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();
?>
出力:
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
?>
構文は次のとおりです。
self::$a