问个子类对象直接调用基类内被重载的函数的问题?/// 问题看如下代码?phpclass A{function A(){ $this-nN
问个子类对象直接调用基类内被重载的函数的问题?
/// 问题看如下代码
<?php
class A
{
function A()
{
$this->nNum = 1024;
}
function SelfClass()
{
echo "class A<br>";
}
}
class B extends A
{
function SelfClass()
{
echo "class B<br>";
}
}
?>
<?php
$obj = new B();
$obj->SelfClass(); // 调用B类的函数SelfClass()函数
/* 如何能使用对象obj的基类的SelfClass()函数?
C++下可以写类似的代码$obj->A::SelfClass(),那么PHP可以如何实现呢?*/
?>
[解决办法]
没有那么麻烦
<?php
class A
{
function A()
{
$this->nNum = 1024;
}
function SelfClass($a,$b,$c,$d,$e,$f)
{
echo "class A<br>" . $this->nNum . "<br>" . "$a,$b,$c,$d,$e,$f". "<br>";
}
function __call($name, $arguments) {
list($class_name, $function_name) = explode('_', $name);
if(is_subclass_of($this, $class_name))
{
//反射一个方法
$reflectionMethod = new ReflectionMethod($class_name, $function_name);
// 使用当前对象调用
$reflectionMethod->invokeArgs($this, $arguments);
}
}
}
class B extends A
{
function B()
{
$this->nNum = 2048;
}
function SelfClass()
{
echo "class B<br>" . $this->nNum . "<br>";
}
}
class C extends B
{
function C()
{
$this->nNum = 4096;
}
function SelfClass()
{
echo "class C<br>" . $this->nNum . "<br>";
}
}
$obj = new B();
$obj->SelfClass(); // 调用B类的函数SelfClass()函数
$obj->A_SelfClass(1,2,3,4,5,6,7);
$obj = new C();
$obj->SelfClass(); // 调用C类的函数SelfClass()函数
$obj->A_SelfClass(1,2,3,4,5,6,7);
$obj->B_SelfClass();