class var private static __get __set
<?php class classname { var $myName; var $myAge; function __construct($name,$age) { //代码 $this->myName=$name; $this->myAge=$age; } function getName() { return $this->myName; } function getAge($arg1,$arg2) { return $this->myAge . $arg1 . $arg2; } } $a=new classname("Jim",10); echo '<br>'; echo $a->getName(); echo '<br>'; echo $a->getAge(' years',' old!'); echo '<br>'; $a->myName="hello"; $a->myAge=100; echo '<br>'; echo $a->getName(); echo '<br>'; echo $a->getAge(' years',' old!'); echo '<br>'; /* Jim 10 years old! hello 100 years old! */
<?php class classname { var $myAttrib; //定义属性 function __get($attribName) //获取属性值的函数 { echo '__get(...)<br>'; return $this->$attribName; //返回该属性值 } function __set($attribName,$value) //设置属性值的函数 { echo '__set(...)<br>'; $this->$attribName=$value; //设置属性值 } } $a=new classname; $a->myAttrib="ABCDEFG"; echo '----------------------<br>'; echo $a->__get('myAttrib'); echo '======================<br>'; echo $a->__set('myAttrib','BCDA'); echo '----------------------<br>'; echo $a->myAttrib; echo '<br>'; /* ---------------------- __get(...) ABCDEFG ====================== __set(...) -
<?php class classname { private $myAttrib; //定义属性 function __get($attribName) //获取属性值的函数 { echo '__get(...)<br>'; return $this->$attribName; //返回该属性值 } function __set($attribName,$value) //设置属性值的函数 { echo '__set(...)<br>'; $this->$attribName=$value; //设置属性值 } } $a=new classname; $a->myAttrib="ABCDEFG"; echo '----------------------<br>'; echo $a->__get('myAttrib'); echo '======================<br>'; echo $a->__set('myAttrib','BCDA'); echo '----------------------<br>'; echo $a->myAttrib; echo '<br>'; /* __set(...) ---------------------- __get(...) ABCDEFG ====================== __set(...) -----------
<?php //class_static_var.php class A{ public static $a = 5; public $b = 4; public function getA(){ return A::$a; } public function setA($val){ A::$a = $val; } public function getB(){ return $this->b; } public function setB($val){ $this->b = $val; } public static function getbb(){ return $this->a; } } $a = new A(); echo $a->getA();//5 $a->setA('aaaa'); echo '<br/>'; //A::$a='bbbb'; $b = new A(); echo $b->getA();//aaaa echo '<br/>'; $c = new A(); echo $c->getA();//aaaa /* 上面的执行结果会是:5 aaaa aaaa 类的对象$a将类的静态成员变量值修改后,由于类的所有实例对象共享静态成员变量,所以其他对象在获取静态成员变量值时就会发生改变。 */ echo '<br>========================================<br>'; $a = new A(); echo $a->getB();//4 $a->setB('aaaa'); echo '<br/>'; $b = new A(); echo $b->getB();//4 /* 上面的执行结果是:4 4 */ echo '<br>========================================<br>'; //echo A::getbb(); /* 会发生报错,因为类的静态方法只能访问静态成员变量 */