2

我有一个父类,它包含一个图像路径的公共变量,它是通过类构造函数设置的

abstract class Parent_Class {
     protected $image_path;

     public function __construct($image_path_base) {
         $this->image_path = $image_path_base . '/images/';         
    }
}

基本路径取决于子类或更确切地说是它们的文件位置。

class ChildA_Class {
    public function __construct() {
         parent::__construct(dirname(__FILE__));         
         ...
    }
}

class ChildB_Class {
    public function __construct() {
        parent::__construct(dirname(__FILE__));
        ...         
    }
}

有没有办法消除dirname(__FILE__)子类中的逻辑并将逻辑移向父类?

4

1 回答 1

1

What you want to do seems strange to me, but here is one possible solution to your problem using reflection and late static binding.

abstract class ParentClass
{
    protected $imagePath;

    public function __construct()
    {
        // get reflection for the current class
        $reflection = new ReflectionClass(get_called_class());

        // get the filename where the class was defined
        $definitionPath = $reflection->getFileName();

        // set the class image path
        $this->imagePath = realpath(dirname($definitionPath) . "/images/");
    }
}

Every child class would automatically have an image path based on where the child class was defined.

于 2013-04-22T18:47:38.797 回答