V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
hiboshi
V2EX  ›  PHP

php 面向对象不解

  •  
  •   hiboshi · 2015-05-29 14:38:57 +08:00 · 2510 次点击
    这是一个创建于 3247 天前的主题,其中的信息可能已经有所发展或是发生改变。

    <?php
    class a extends b {
    public function init() {
    echo "init.a";
    }
    }
    class b {
    public function __construct (){
    echo "string";
    }
    function test() {
    echo "aa";
    $this->init();
    }
    public function init() {
    echo "init.b";
    }
    }
    $aa = new a();
    $aa->test();

    为何不执行b.init(),难道 this 访问的时候B 不是对象?

    9 条回复    2015-05-29 15:10:17 +08:00
    ob
        1
    ob  
       2015-05-29 14:48:51 +08:00
    哈哈,我来猜测一下:
    a继承自b,那么b的所有方法都会被a继承,包括test(),所以当$aa->test()的时候,$this其实还是a自己的。
    hiboshi
        2
    hiboshi  
    OP
       2015-05-29 14:49:04 +08:00
    了解了 忘记 被覆盖了
    cevincheung
        3
    cevincheung  
       2015-05-29 14:50:00 +08:00
    a继承b。a的init覆盖(重写)了b的init。所以调用a的init就只是调用a的init。
    百度:php parent

    ps: 敢不敢好好处理一下缩进,看的蛋疼
    hiboshi
        4
    hiboshi  
    OP
       2015-05-29 14:50:57 +08:00
    @ob 如果解释称 a 继承 b 覆盖了 a的init方法这样 更好点
    hiboshi
        5
    hiboshi  
    OP
       2015-05-29 14:51:19 +08:00
    @hiboshi 覆盖了b 的init
    Paranoid
        6
    Paranoid  
       2015-05-29 15:02:20 +08:00
    $aa = new a(); 返回对象是A, $aa->test(); 调用 A 的test() , 有该方法? 没有, 父类有,调用,父类中方法中的 $this->init(); $this 是对象A. 对象A 有 init() 方法? 有调用 。
    anyforever
        7
    anyforever  
       2015-05-29 15:04:47 +08:00
    @cevincheung +1
    楼主还得好好学一下基础啊。
    hiboshi
        8
    hiboshi  
    OP
       2015-05-29 15:09:16 +08:00
    @anyforever 短路了
    anyforever
        9
    anyforever  
       2015-05-29 15:10:17 +08:00
    @hiboshi 呃、哈哈。外面抽一根儿回来就满血了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3369 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 11:42 · PVG 19:42 · LAX 04:42 · JFK 07:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.