abstract class Foo
{
pulbic function __construct()
{
if (method_exists($this, 'beforeConstruct')) {
$this->beforeConstruct();
}
if (method_exists($this, 'afterConstruct')) {
$this->afterConstruct();
}
}
}
class Bar extends Foo
{
public function beforeConstruct()
{
echo 'Before Construct.<br>';
}
public function __construct()
{
echo 'Clas Bar has been created.<br>'
}
public function beforeConstruct()
{
echo 'After Construct.<br>';
}
}
$bar = new Bar();
但没有工作,有人可以帮助我吗?如何返回这样的结果:
施工前。
已经创建了Class Bar。
构造后。
答案 0 :(得分:0)
首先从子类constructor
调用父的constructor
,后者又调用子类的方法beforeConstruct()
,然后调用它在它激发你的子类的Clas Bar has been created.
之后打印destructor
。
<?php
abstract class Foo
{
public function __construct()
{
if (method_exists($this, 'beforeConstruct')) {
$this->beforeConstruct();
}
if (method_exists($this, 'afterConstruct')) {
$this->afterConstruct();
}
}
}
class Bar extends Foo
{
public function __construct()
{
parent::__construct();
echo 'Clas Bar has been created.<br>';
}
public function beforeConstruct()
{
echo 'Before Construct.<br>';
}
public function __destruct()
{
echo 'After Construct.<br>';
}
}
$bar = new Bar();
<强> OUTPUT:
强>
Before Construct. Clas Bar has been created. After Construct.