PHP:this作用、类定义以及调用、构造方法、析构方法、this调用属性和方法

$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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值