2017-06-04 24 views
1

ツリー内の各クラスが独自のディレクトリでテンプレートをチェックして使用するクラスツリーを作成しようとしましたが、継承されたクラスで関数を呼び出してからparentと呼ばれました。どうすればいいですか?PHP:継承に関する問題

マイ出力以下の例のコード

D
C
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関数を再定義することなく、parent:check_templateが定義されている最初の親クラスを呼び出します。 – anry

+0

私はクラスツリーの各クラスを自分のテンプレートdirにテンプレートを見つけたいと思っています。もしテンプレートがない場合は、このテンプレートを自分の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');