2017-06-04 52 views
1

我尝试做类树,其中树中的每个类检查模板的自己的目录并使用它,但是当我在继承的类中调用函数,然后调用父类。我该怎么做 ?PHP:继承问题

我的例子下面输出在代码:

d
Ç
B/1.phtml

但我需要d/1.phtml

<?php 

class A { 
    private $templates_dir = 'a'; 
} 

class B extends A { 

    private $templates_dir = 'b'; 

    public function templates_dir() 
    { 
     return $this->templates_dir; 
    } 

    public function check_template($tpl) 
    { 
     $dir = $this->templates_dir(); 
     $file = $dir. '/'. $tpl; 
     echo (get_class($this)). "\r\n"; 
     echo (get_parent_class($this)). "\r\n"; 
     echo $file . "\r\n"; 
// idea - if (!file_exists($file)) return parent::check_template($file); 
// method call each class while template will be found 
// how do it? 


    } 

} 

class C extends B { 

    private $templates_dir = 'c'; 

} 

class D extends C { 

    private $templates_dir = 'd'; 

} 

$obj = new D(); 
$obj->check_template('1.phtml'); 
+0

与所有那些你在痛苦的世界进入的子类。 – Federkun

回答

1

我只想让$templates_dir受保护:

class A { 
    protected $templates_dir = 'a'; 
} 

并调整扩展类来执行相同操作。

然后这会导致templates_dir()返回任何$templates_dir设置为。

+0

谢谢,它是templates_dir的解决方案,但主要思想是重新定义模板,并且不需要在每个调用父类的子类中重新定义函数check_template:check_template调用首先定义的父类。 – anry

+0

我希望类树中的每个类都在自己的模板中找到模板目录,并且如果没有模板调用直接父类用于在自己的templates_dir中检查此模板,并且直到找到模板 – anry

1

另一种方法是将函数放在一个抽象类中,并且A,B,C,D类中的每一个扩展它,这是一个更好的方法。

下面是代码 -

abstract class WW { 

    protected function templates_dir() 
    { 
     return $this->templates_dir; 
    } 

    public function check_template($tpl) 
    { 
     $dir = $this->templates_dir(); 
     $file = $dir. '/'. $tpl; 
     echo (get_class($this)). "\r\n"; 
     echo (get_parent_class($this)). "\r\n"; 
     echo $file . "\r\n"; 
    // idea - if (!file_exists($file)) return parent::check_template($file); 
    // method call each class while template will be found 
    // how do it? 


    } 
} 

class A extends WW { 
    protected $templates_dir = 'a'; 
} 

class B extends WW { 

    protected $templates_dir = 'b'; 



} 

class C extends WW { 

    protected $templates_dir = 'c'; 

} 

class D extends WW { 

    protected $templates_dir = 'd'; 



} 

$obj = new D(); 
$obj->check_template('1.phtml');