2013-02-14 60 views
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__)和对父类移动逻辑的方法吗?

+0

不要硬编码路径,而是将其作为参数传递给 – KingCrunch 2013-02-14 13:27:05

+0

作为子类中的parent :: __构造(dirname(__ FILE__)。'/ images /')? – SunnyRed 2013-02-14 13:42:24

+1

这可能与反思,但我不会推荐它。根据类文件的位置设置图像路径似乎是错误的。你不分离代码和其他资源吗? – 2013-02-15 12:19:06

回答

1

你想要做的事对我来说似乎很陌生,但这里有一个可能的解决方案,用你的问题使用反射和后期静态绑定。

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/"); 
    } 
} 

每个子类都会根据子类的定义位置自动生成一个图像路径。

相关问题