PHP中的$this关键字

来源:互联网 发布:类似魔镜的软件 编辑:程序博客网 时间:2024/06/07 19:16

下文为转载,仅为收藏标记用。原地址:http://www.web589.com/posts/856.html

为了解决php类和对象中变量与属性的命名冲突和不确定性问题,引入了”$this”关键字来调用当前的对象。

  • 在类中调用当前对象的属性和方法,必须使用”$this->”关键字;
  • $this在构造函数中指该构造函数所创建的新对象;
  • 方法内的局部变量不属于对象,不使用$this关键字取值。

使用$this关键字,我们可以在类中调用对象属性或者方法。

1、调用变量

实例:

<?php class user{private $n;function __construct(){$name="Mike";echo $this->n=$name;}}$p=new user();?>



运行结果:

$this关键字 php类和对象

2、调用方法

实例:


<?php class cal{public function sum($a,$b){return $a+$b;}public function prt($a,$c){return $a*$c;}public function result($a,$b,$c){$a=$this->sum($a,$b);return $this->prt($a,$c);}}$c=new cal();echo "(2+3)*10= " .$c->result('2','3','10');?>



运行结果:

$this关键字 php类和对象

原创粉丝点击