PHP进修笔记二: 面向对象设计

    添加时间:2013-5-14 点击量:
    public 默示全局,类内部外部子类都可以接见;



     1 <?php
    
    2
    3 class Test{
    4 public ¥name=Janking,
    5 ¥sex=male,
    6 ¥age=23;
    7
    8 function __construct(){
    9 echo ¥this->age.<br />.¥this->name.<br />.¥this->sex.<br />;
    10 }
    11
    12 function func(){
    13 echo ¥this->age.<br />.¥this->name.<br />.¥this->sex.<br />;
    14 }
    15 }
    16
    17
    18 ¥P=new Test();
    19 echo <br /><br />;
    20 ¥P->age=100;
    21 ¥P->name=Rainy;
    22 ¥P->sex=female;
    23 ¥P->func();
    24 ?>


    Public

    private默示私有的,只有本类内部可以应用;



     1 <?php
    
    2
    3 class Test{
    4 private ¥name=Janking,
    5 ¥sex=male,
    6 ¥age=23;
    7
    8 function __construct(){
    9 ¥this->funcOne();
    10 }
    11
    12 function func(){
    13 echo ¥this->age.<br />.¥this->name.<br />.¥this->sex.<br />;
    14 }
    15
    16 private function funcOne(){
    17 echo ¥this->age.<br />.¥this->name.<br />.¥this->sex.<br />;
    18 }
    19 }
    20
    21
    22 ¥P=new Test();
    23 echo <br /><br />;
    24 ¥P->func();
    25 ¥P->age=100; // Cannot access private property Test::¥age
    26 ¥P->name=Rainy; // Cannot access private property Test::¥name
    27 ¥P->sex=female; // Cannot access private property Test::¥female
    28 ¥P->funcOne(); // Call to private method Test::funcOne() context
    29 ?>


    Private

    protected默示受保护的,只有本类或子类或父类中可以接见;



     和封装有关的魔术办法:

     __set():是直接设置私有成员属性值时,主动调用的办法
     __get():是直接获取私有成员属性值时,主动调用的办法
     __isset(); 是直接isset查看对象中私有属性是否存时主动调用这个办法
     __unset(); 是直接unset删除对象中私有属性时,主动调用的办法


     
    所有随风而逝的都属于昨天的,所有历经风雨留下来的才是面向未来的。—— 玛格丽特·米切尔 《飘》
    分享到: