示例#1
0
<?php

class MyObj
{
    public static $instance = 0;
    public function myMethod()
    {
        self::$instance += 2;
        echo self::$instance . '<br/>';
    }
}
class MyOtherObj extends MyObj
{
    public static $instance = 0;
    public function myOtherMethod()
    {
        echo parent::$instance . '<br/>';
        // parent 指代父类
        echo self::$instance . '<br/>';
        // self 表示本身类
    }
}
$instance1 = new MyObj();
$instance1->myMethod();
// 2
$instance2 = new MyObj();
$instance2->myMethod();
// 4
$instance3 = new MyOtherObj();
$instance3->myOtherMethod();
// 4,0
示例#2
0
    public static $myStaticVar = 0;
    function myMethod()
    {
        self::$myStaticVar += 2;
        echo self::$myStaticVar . '<br/>';
    }
}
$instance1 = new MyObject();
$instance1->myMethod();
$instance2 = new MyObject();
$instance2->myMethod();
echo '<hr/>';
class MyObj
{
    function myBaseMethod()
    {
        echo "I am declared in MyObject<br/>";
    }
}
class MyOtherObj extends MyObj
{
    function myExtendedMethod()
    {
        echo 'myExtendedMethod id declared in MyOtherObj <br/>';
        self::myBaseMethod();
        // 在这里 self 和 parent 作用一样
        //parent::myBaseMethod();
    }
}
MyOtherObj::myExtendedMethod();