class A{ private $a = 99; //打印参数的方法 public function printInt($a){ echo "这里的\$a是传递参数的$a "; echo "<br>"; echo "这里的\$this->a 是属性 $this->a"; } }
$a = new A(); $a->printInt(88); ?>
<? //用$this调用对象中的其它方法 class Math{ //两个数值比较大小 public function Max($a,$b){ return $a>$b?$a:$b; } //三个数比较大小 public function Max3($a,$b,$c){ $a = $this->Max($a,$b); return $this->Max($a,$c); } } $math = new Math(); echo "最大值是 ".$math->Max3(99,100,88); ?>
<? //使用$this调用构造函数 //调用构造函数和析构函数的方法一致。 class A{ private $a = 0; public function __construct(){ $this->a = $this->a+1; }
public function doSomeThing(){ $this->__construct(); return $this->a; } }
$a = new A(); echo "现在\$a的值是".$a->doSomeThing(); ?>
<? //$this 到底指的什么? //$this 就是指当前对象,我们甚至可以返回这个对象使用 $this class A{ public function getASelf(){ return $this; } public function __toString(){ return "这是类A的实例"; } }
$a = new A(); $b = $a->getASelf();//调用方法返回当前实例 echo $a;//打印对象会调用它的__toString方法 ?>