php學習九:存取器&魔術方法

來源:互聯網
上載者:User

標籤:方法調用   檢驗   isset   else   amp   dog   getname   val   student   

當聲明屬性的時候用到了private,那麼的話只能本類中才能訪問此屬性,其他地方無法使用,這個時候需要給外界提供一些方法來使外界訪問

方法一:存取器:

可以提供一個public的方法來使外界對類裡面的屬性進行訪問和賦值

class Student{    private $name;    private $age;    public function show(){        echo "{$this->name}今年{$this->age}歲了";    }    /*****存取器:get,set******/    /****提供set方法給外界賦值***/    public function setName($name){        $this->name=$name;    }    public function setAge($age){        if($age<0){            $this->age = "18";        }else{            $this->age=$age;        }    }    /******提供get方法給外界取值**********/    public function getName(){        return $this->name;    }    public function getAge(){        return $this->age;    }}

 執行個體化的代碼:

$stu = new Student();/*****不能直接存取,需要用類裡面的set,get方法來訪問******/$stu->setName("房明");echo $stu->getName();$stu->setAge(-18);echo $stu->getAge();$stu->show();

  

方法二:魔術方法進行訪問

在php中文誒我們提供了許多的魔術方法,在這裡我們只要是某某一個魔術方法就可以完成我們想要的效果

*__set():賦值
* __get():取值
* __isset():是否有這個屬性
* __unset():銷毀某個屬性

代碼如下:
class User{    private $name;    private $age;    /*****__set():賦值****/    function __set($name,$value)    {        if($name == "age"){            if($value <18){                $this->age = 18;            }else{                $this->age = $value;            }        }else{            $this->$name = $value;        }    }    /****__get():取值***/    function __get($name)    {        if($name == "name"){            return "dog";        }else{            return $this->$name;        }    }    /***** __isset():是否有這個屬性****/    //噹噹前屬性被isset()或者empty(),即當某個屬性被檢驗空的方法調用的時候,會觸發這個方法    function __isset($name)    {        echo "{$name}isset被調用了";    }    /*******__unset():銷毀某個屬性******/    //    function __unset($name)    {        echo "{$name}被銷毀了";        //防止被銷毀的時候直接寫一個return即可;    }    public function show(){        echo "{$this->name}今年{$this->age}歲了";    }}

  魔術方法進行訪問:

$user = new User();$user->name = "房明";$user->age = 10;echo $user->name;echo $user->age;$user->show();isset($user->name);unset($user->name);

  

php學習九:存取器&魔術方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.