為什么是9呢?不解
<?php
class test{
? ? protected $a=9,$b=2,$c;
? ? public $d;
? ? function __set($n,$v){
? ? ? ? return $this->$n=$v+2;
? ? }
? ? function __get($name){
? ? ? return $this->$name+2; ?
? ? }
}
?$a=new test();
?$a->b=5;
?echo $a->b;
<?php
class test{
? ? protected $a=9,$b=2,$c;
? ? public $d;
? ? function __set($n,$v){
? ? ? ? return $this->$n=$v+2;
? ? }
? ? function __get($name){
? ? ? return $this->$name+2; ?
? ? }
}
?$a=new test();
?$a->b=5;
?echo $a->b;
2016-10-22
舉報
2016-10-22
$a->b=5 ?執行的是 __set($n,$v); ?return $this->$n=$v+2; ?這里a對象中的$b屬性進行5+2=7的賦值。最后你輸出echo $a->b 時執行__get($name)?? return $this->$name+2; ? 又加了2 ?所以是9 。 這跟類中你自己定義的$b=2 ,無關 。因為你給它重新賦值了。
2016-10-22
你首先創了一個 類test()的對象$a,后又創了一個類test()中不存在的屬性b,你要對b賦值并輸出,所以你的類中有__set(),__get,兩個函數,在對b賦值時就訪問了賦值函數__set(),輸出時既訪問了讀取函數__get..........個人看法,哈哈
2016-10-22
你首先創了一個 類test()的對象$a,后又創了一個類test()中不存在的屬性b,你要對b賦值并輸出,所以你的類中有__set(),__get,兩個函數,在對b賦值時就訪問了賦值函數__set(),輸出時既訪問了讀取函數__get..........個人看法,哈哈
2016-10-22
你首先創了一個 類test()的對象$a,后又創了一個類test()中不存在的屬性b,你要對b賦值并輸出,所以你的類中有__set(),__get,兩個函數,在對b賦值時就訪問了賦值函數__set(),輸出時既訪問了讀取函數__get..........個人看法,哈哈