2010年8月2日 星期一

[PHP] Visibility

http://www.php.net/manual/en/language.oop5.visibility.php

<?php
/**
 * Define MyClass
 */
class MyClass
{
    public $public = 'Public';
    protected $protected = 'Protected';
    private $private = 'Private';

    function printHello()
    {
        echo $this->public."<br>";
        echo $this->protected."<br>";
        echo $this->private."<br>";
    }
}

$obj = new MyClass();
echo $obj->public."<br>"; // Works
//echo $obj->protected."<br>"; // Fatal Error
//echo $obj->private."<br>"; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private


/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    // We can redeclare the public and protected method, but not private
    protected $protected = 'Protected2';

    function printHello()
    {
        echo $this->public."<br>";
        echo $this->protected."<br>";
        echo $this->private."<br>";
    }
    
    function parentHello()
    {
     parent::printHello();
    }
}

$obj2 = new MyClass2();
echo $obj2->public."<br>"; // Works
echo $obj2->private."<br>"; // Undefined
//echo $obj2->protected."<br>"; // Fatal Error
$obj2->printHello(); // Shows Public, Protected2, Undefined
$obj2->parentHello();
?>


Result:
Public
Public
Protected
Private
Public
Notice: Undefined property: MyClass2::$private in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\global.php on line 49 
Public
Protected2
Notice: Undefined property: MyClass2::$private in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\global.php on line 38 
Public
Protected2
Private
Related Posts Plugin for WordPress, Blogger...