2013-04-23 87 views
6

我正在學習OOP,並且非常混淆地爲對方使用類。PHP包含其他類中的類

我有共有3類

//CMS System class 
class cont_output extends cont_stacks 
{ 
    //all methods to render the output 
} 


//CMS System class 
class process 
{ 
    //all process with system and db 
} 


// My own class to extends the system like plugin 
class template_functions 
{ 
    //here I am using all template functions 
    //where some of used db query 
} 

現在我想用我自己的類template_functions withing兩個系統類。但非常困惑如何使用它。請幫我理解這一點。

編輯: 對不起香榭麗我忘了提及我自己的類在不同的PHP文件。

+0

我感到困惑的是什麼你的困惑... – raidenace 2013-04-23 16:58:41

+0

聽起來好像要多繼承,使cont_output同時擴展cont_stacks和template_functions?因爲否則,沒有理由class#1不能調用一個靜態方法,或者在它自己內部實例化一個class#2的副本。 – 2013-04-23 17:05:47

+0

@MarcB這是一種,但只取決於我是如何使用我自己的類在兩個類中可用。 – 2013-04-23 17:10:13

回答

10

首先,要肯定的是,在使用它之前,你include類文件:

include_once 'path/to/tpl_functions.php'; 

這應該無論是在你的index.php文件或在其上使用tpl_function類的頂部來完成。還請注意autoloading類別的可能性:

由於PHP5您必須自動加載類。這意味着你註冊一個鉤子函數,當你嘗試使用一個尚未包含代碼文件的類時,它每次都被調用。這樣做你不需要在每個類文件中都有include_once語句。這裏談到一個例子:

的index.php或任何應用程序入口點:

spl_autoload_register('autoloader'); 

function autoloader($classname) { 
    include_once 'path/to/class.files/' . $classname . '.php'; 
} 

從現在起,您可以訪問類,而不必擔心包括代碼的文件了。試試看:

$process = new process(); 

認識到這一點,有幾種方法,你如何使用template_functions


只是使用它

您可以訪問類代碼的任何部分,如果您創建它的一個實例:

class process 
{ 
    //all process with system and db 

    public function doSomethging() { 
     // create instance and use it 
     $tplFunctions = new template_functions(); 
     $tplFunctions->doSomethingElse(); 
    } 
} 

實例成員:

以進程類爲例。爲了使template_functions可用process類中,創建一個實例成員和地方初始化它,在你需要它的構造似乎是一個好地方:

//CMS System class 
class process 
{ 
    //all process with system and db 

    // declare instance var 
    protected tplFunctions; 

    public function __construct() { 
     $this->tplFunctions = new template_functions; 
    } 

    // use the member : 

    public function doSomething() { 
     $this->tplFunctions->doSomething(); 
    } 


    public function doSomethingElse() { 
     $this->tplFunctions->doSomethingElse(); 
    } 
} 
+0

感謝您的快速反應..只是幾個更多的查詢..保護是一個變量,所以它需要'$'?我忘了在單獨的php文件中提到我的課程 – 2013-04-23 17:03:53

+0

那麼包含我的文件的地方在哪裏? – 2013-04-23 17:07:13

+0

檢查我的更新 – hek2mgl 2013-04-23 17:07:51

0

可以擴展template_functions類,則可以使用所有的功能。

class cont_output extends cont_stacks //cont_stacks has to extend template_functions 
{ 
    public function test() { 
     $this->render(); 
    } 
} 


class process extends template_functions 
{ 
    public function test() { 
     $this->render(); 
    } 
} 


class template_functions 
{ 
    public function render() { 
     echo "Works!"; 
    } 
} 
+0

但是比'class process'還要多嗎?抱歉,但試圖理解 – 2013-04-23 17:04:46