Home  >  Article  >  Backend Development  >  对这个打印的结果有点不明白?

对这个打印的结果有点不明白?

WBOY
WBOYOriginal
2016-06-06 20:17:051160browse

为什么cry是用的祖父的方法 而age和leg却是用的自己的属性?这是为什么?而我输出man::t1()却全是用的祖父的方法和属性

<code><?php class Animal{
    const age=1;
    public static $leg=4;
    public static function cry(){
        echo "1111";
    }
    public static function t1(){
        self::cry();
        echo self::age;
        echo self::$leg;
    }
    public static function t2(){
        self::cry();
        echo static::age;
        echo static::$leg;
    }
}
class human extends Animal{
    const age=30;
    public static $leg=2;
    public static function cry(){
        echo "5555";
    }
}
class man extends human{
    const age=16;
    public static $leg=1;
    public static function cry(){
        echo "aaaa";
    }
}

man::t2();
?></code>

回复内容:

为什么cry是用的祖父的方法 而age和leg却是用的自己的属性?这是为什么?而我输出man::t1()却全是用的祖父的方法和属性

<code><?php class Animal{
    const age=1;
    public static $leg=4;
    public static function cry(){
        echo "1111";
    }
    public static function t1(){
        self::cry();
        echo self::age;
        echo self::$leg;
    }
    public static function t2(){
        self::cry();
        echo static::age;
        echo static::$leg;
    }
}
class human extends Animal{
    const age=30;
    public static $leg=2;
    public static function cry(){
        echo "5555";
    }
}
class man extends human{
    const age=16;
    public static $leg=1;
    public static function cry(){
        echo "aaaa";
    }
}

man::t2();
?></code>

t1() 里面写的都是self当然都是调用祖父自己的。

t2() 里面self调用祖父自己的cry(),由于属性用了static声明(后静态绑定)。就调用到了man自己的属性。

self...

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn