$this作用:
1.永远代表本对象
类定义以及调用
<?php
// 类
class Person{
// 属性
public $name='user123';
// 方法
public function say(){
echo '<p>my name is user123</p>';
}
}
$obj=new Person();
//调用对象的方法
$obj->say();
//调用对象的属性
echo $obj->name;
?>
**
my name is user123
user123
this的作用
<?php
// 类
class Person{
// 属性
public $name='user456';
// 方法
public function say(){
echo "<p>my name is {$this->name}</p>";
}
}
$obj=new Person();
//调用对象的方法
$obj->say();
?>
**
my name is user456
构造方法:
public function __construct(){
#对象在诞生之前会触发
}
构造方法
<?php
// 类
class Person{
// 属性
public $name;
// 构造方法
public function __construct($n){
$this->name=$n;
}
// 方法
public function say(){
echo "<p>my name is {$this->name}</p>";
}
}
$obj=new Person('uers1');
//调用对象的方法
$obj->say();
?>
**
my name is uers1
析构方法:
public function __destruct(){
#对象在消失之前会触发
}
构造方法
<?php
// 类
class Person{
// 属性
public $name;
// 构造方法
public function __construct($n){
$this->name=$n;
}
// 方法
public function say(){
echo "<p>my name is {$this->name}</p>";
}
//析构方法
public function __destruct(){
echo"<p>{$this->name}要走了啦!</p>";
}
}
$obj=new Person('uers1');
$obj->say();
$obj2=new Person('uers2');
$obj2->say();
$obj3=new Person('uers3');
$obj3->say();
?>
结果是-栈-堆-先进后出
my name is uers1
my name is uers2
my name is uers3
uers3要走了啦!
uers2要走了啦!
uers1要走了啦!
this调用属性和方法
this调用属性和方法
<?php
// 类
class Person{
// 属性
public $name;
// 构造方法
public function __construct($n){
$this->name=$n;
}
// 调用属性
public function get(){
return $this->name;
}
// 方法
public function say(){
echo "my name is ".$this->get();
}
}
$obj=new Person('uers1');
$obj->say();
**
my name is uers1