UPDATE
在阅读您的问题第二次,我刚刚想到了另一种方式,是你需要的东西更适合。尽管php不支持多继承,并且特性需要php> = 5.4,但您可能需要考虑添加第二代“代”(另一层儿童)。抽象类仅包含所有可用的方法,最好使用final
关键字,或者只在该行的某个位置有1个变体(在这种情况下,放弃final
关键字并覆盖成员函数)。
正如我以前说过的,我不解释这个东西,不错,所以我提前去上你的课怎么可能看起来像一个放在一起的例子:
abstract class User
{
public function __construct()
{
echo get_class($this).'<br/>';
}
final function forAll()
{
echo 'access for all';
}
}
class TxtGroup extends User
{
public function __construct()
{
parent::__construct();
}
public function abstr()
{
echo 'TxtGroup specific';
}
}
class ImgGroup extends User
{
public function __construct()
{
echo 'Same, but different for ImgGroup<br/>';
parent::__construct();
}
public function abstr()
{
echo 'ImgGroup specific';
}
}
class inst1 extends TxtGroup
{
public function __construct()
{
parent::__construct();
if ($this instanceof TxtGroup)
{
echo 'Child member of: TxtGroup<br/>';
}
if ($this instanceof inst1)
{
echo 'Child instance of inst1 (itself)<br/>';
}
if ($this instanceof User)
{
echo 'grand-Child of User<br/>';
}
}
public function objSpecific()
{
echo 'self explanatory<br/>';
}
}
class inst2 extends ImgGroup
{
public function __construct()
{
parent::__construct();
if ($this instanceof ImgGroup)
{
echo 'Child member of: ImgGroup<br/>';
}
if ($this instanceof inst2)
{
echo 'Child insance of inst2 (itself)<br/>';
}
if ($this instanceof User)
{
echo 'grand-Child of User<br/>';
}
}
}
$foo = new inst1();
$bar = new inst2();
看看我意思?输出:
INST1
子成员的:TxtGroup用户
相同的INST1的
儿童实例(本身)
盛大孩子,但不同的ImgGroup
INST2
的 子成员:ImgGroup
INST1的儿童insance(本身)
用户的盛大孩子
如果您使用的是最新版本的PHP,那么您就有这种特质。有很多方法可以检查哪个类正在调用成员函数。最简单的,海事组织,是通过检查get_class($this);
值开始你的方法:
abstract class Foo
{
public function who()
{
echo get_class($this);
}
}
class bar extends Foo
{
public function __construct()
{
$this->who();
}
}
$f = new bar();
回声的bar
,这样你就可以改变的抽象方法,并在必要时抛出异常。
同样的结构可用于重载某些方法,像这样的(可怕的)例子(试图展示/)显示:
abstract class Foo
{
public function who()
{
$child = explode('_',get_class($this));
if (end($child) === 'whoExec')
{
return $this->whoExec();
}
echo 'this isn\'t for bar the bar instance';
return $this;
}
private function whoExec()
{
if(!strstr('whoExec',get_class($this)))
{
return $this->who();
}
echo 'This methods mimics overloading -sort of';
return $this;
}
}
class bar_whoExec extends Foo
{
public function __construct()
{
$this->who();
}
}
$f = new bar();
我不知道如何使用特点,但我检查了在手册。我有从c + +/java的背景,所以不确定实际使用的特征。感谢这个想法。 – varuog 2012-08-10 08:13:55
@ user1538127:我刚刚添加了一个更简单的替代方案,它适用于5.4之前的版本。 PS:如果你在C++/java中有背景,可以把特征看作是部分继承 – 2012-08-10 09:47:14