PHP中的Before and After构造方法类


Before and After Contruct Method Class in PHP

库克看起来像这样:

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已经创建。

施工后。

首先从子类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.