1

当我运行以下代码时,我得到B了预期:

class A {
    public function __construct($file){}
}

class B extends A {
    public function __construct() {
        parent::__construct('test.flv');
    }
}

$b = new B();
print get_class($b);

但是,请考虑对这段代码稍作修改的版本(这里ffmpeg_movie的类是http://ffmpeg-php.sourceforge.net库的一部分):

class B extends ffmpeg_movie {
    public function __construct() {
        parent::__construct('test.flv');
    }
}

$b = new B();
print get_class($b);

它返回ffmpeg_movie而不是B. 此外,事实证明B在使用$b对象时无法访问类中定义的方法:

class B extends ffmpeg_movie {
    public function __construct() {
        parent::__construct('test.flv');
    }

    public function test() {
        print 'ok';
    }
}

$b = new B();
$b->test();

Fatal error: Call to undefined method ffmpeg_movie::test() in .../test.php on line 13

这里到底发生了什么,是否有解决方法?

4

2 回答 2

1

I didn’t find out what was the origin of the problem. I managed to solve it though by not extending ffmpeg_movie class directly and instead using __call, __get and __set PHP magic methods to mimic inheritance.

于 2012-06-27T17:17:55.867 回答
0

这是 get_class() 的未定义行为,之前已经讨论过很多次。

自 PHP 4.3.0 起,常量CLASS存在并包含类名。

在有人提出解决方案之前,您可能会在 B 类中摆弄类似这样的东西:

public function whoAmI() {
    return __CLASS__;
}

或者(来自谷歌搜索)也许

public function whoAmI() {
    return getClass($this);
}
于 2012-06-22T18:16:07.413 回答