Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PHP面向对象--构造方法和析构方法 #18

Open
hubvue opened this issue Dec 22, 2018 · 0 comments
Open

PHP面向对象--构造方法和析构方法 #18

hubvue opened this issue Dec 22, 2018 · 0 comments
Labels
PHP Extra attention is needed

Comments

@hubvue
Copy link
Owner

hubvue commented Dec 22, 2018

构造方法

当类被实例化的时候,构造方法调用

构造方法的用途

用于实例化类的时候初始化相关数据。

// 构造方法语法格式
    [修饰符] function__construct([参数]){
        程序体
    }

析构方法

当类不用再使用这个类里面的属性和方法的时候,析构方法执行。

析构方法的用途

可以禁用资源的释放:数据库关闭、读取文件关闭等等,对象被销毁的时候执行,也就是说这个对象没有代码再运行了。

//析构方法方法格式
    [修饰符] function__destruct([参数]){
        程序体
    }

构造方法与析构方法的实例

class Test {
    //构造方法
    public function __construct($name , $age){

        echo 'hello'.$name;
        echo"</br>";
        $this -> age =$age;
        $this -> name = $name;
    }
    public function data(){
        return $this -> age;
    }
    //析构方法。
    public function __destruct(){
        echo "bye bye {$this -> name}";
    }
}
$test = new Test('first',20);   
$test = new Test('first',20); 
//对象的执行顺序----先进先出
// echo $test -> data();   //输出20
@hubvue hubvue added the PHP Extra attention is needed label Jan 8, 2019
@hubvue hubvue assigned hubvue and unassigned hubvue Jan 8, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
PHP Extra attention is needed
Projects
None yet
Development

No branches or pull requests

1 participant