之前自己摸索着学习过一段时间的PHP编程,也尝试开发出了基于过程的单用户博客系统Slience. 由于想涉足大中型项目的实战开发,之前学习的那点皮毛根本是杯水车薪,于是趁着工作任务不重,打算系统的学习一下PHP开发。太过基础的内容并没有记在这里,因为都很容易掌握,关于面向对象的解释和理论也并没有放在这里,这里可能要花几篇的篇幅来记录一下对OOP开发过程中会常用到的一些方法和函数的理解。

构造方法 __construct()

这个方法在类被实例化时会被首先调用,因此可借助该方法给类的成员属性赋值, 此方法应该写在类内部的最上方,成员属性的下方:

 class Human{
    
      public $name; // 公开属性
      private $age; // 私有属性
      protected $sex; //受保护属性
      var $height; // 尚未明确类型的属性,暂定

     public function __construct($name,$age,$sex,$height){
        $this->name = $name;
        $this->age = $age;
        $this->sex = $sex;
        $this->height = $height;
        $this->property(); 
        //调用了一个成员方法,当Human被实例化时,自动根据构造函数所赋的值执行property()方法
     }

    // $this 可以用来访问成员属性和成员方法 $this->name; $this->property();

     public function property(){
        echo "<h3>The Property for ".$this->name.":</h3>";
        echo "<li> Name :".$this->name."</li>";
        echo "<li> Age :".$this->age."</li>";
        echo "<li> Sex :".$this->sex."</li>";
        echo "<li> Height :".$this->height."</li>";
     }
     
   }
    
    $jerry =new human('Jerry','28','Male','182cm');
    // 因为在构造方法中我们给成员属性赋了值,所以这里的属性在实例化时即被传入对象中并执行了property()方法

上面的代码会输出

The Property for Jerry:

  • Name :Jerry
  • Age :28
  • Sex :Male
  • Height :182cm

析构方法 __destruct()

和构造方法对应,析构方法只有在执行完当前的所有脚本之后才会被自动调用,因此我们可以借助这个方法来实现一些释放资源,清理数据,保存等操作。析构方法总是定义在成员方法的最末尾的位置。
还是上面的代码,这次我们加上析构方法:

 class Human{
    
      public $name; 
      private $age; 
      protected $sex; 
      var $height; 

     public function __construct($name,$age,$sex,$height){
        $this->name = $name;
        $this->age = $age;
        $this->sex = $sex;
        $this->height = $height;
        $this->property(); 
       
     }

     public function property(){
        echo "<h3>The Property for ".$this->name.":</h3>";
        echo "<li> Name :".$this->name."</li>";
        echo "<li> Age :".$this->age."</li>";
        echo "<li> Sex :".$this->sex."</li>";
        echo "<li> Height :".$this->height."</li>";
     }

    public function __destruct(){ 
        echo "Say Goodbye to ".$this->name;
    }
     
   }
    
    $jerry =new human('Jerry','28','Male','182cm');

上面的代码会输出

The Property for Jerry:

  • Name :Jerry
  • Age :28
  • Sex :Male
  • Height :182cm
    Say Goodbye to Jerry

标签: php, OOP

分享到: