2011-11-20 49 views
6

我有了下一個功能的控制器:將函數的變量傳遞給控制器​​中其他函數的代碼?

class controller { 

    function __construct(){ 

    } 

    function myfunction(){ 
     //here is my variable 
     $variable="hello" 
    } 


    function myotherfunction(){ 
     //in this function I need to get the value $variable 
     $variable2=$variable 
    } 

} 

我感謝你的答案。如何將一個函數的變量傳遞給codeigniter控制器中的其他函數?

+0

另外,根據「myotherfunction」是否可以通過url調用,您可以使用下劃線進行命名,以使其默認情況下不可用,例如'private function _myotherfunction(){}'。 – Matthew

回答

5

或者你也可以設置$變量作爲你的類屬性;

class controller extends CI_Controller { 

    public $variable = 'hola'; 

    function __construct(){ 

    } 

    public function myfunction(){ 
     // echo out preset var 
     echo $this->variable; 

     // run other function 
     $this->myotherfunction(); 
     echo $this->variable; 
    } 

    // if this function is called internally only change it to private, not public 
    // so it could be private function myotherfunction() 
    public function myotherfunction(){ 
     // change value of var 
     $this->variable = 'adios'; 
    } 

} 

這樣變量將提供給你的控制器類中的所有函數/方法。認爲OOP不是程序性的。

+0

這是一個好主意,但是,在mymotherfunction()中,我將打印變量,不顯示值,頁面爲白色。 localhost/myproject/controller/myotherfunction(不要打印echo $ this-> variable),會在構造函數中加載一些嗎? 謝謝。我很抱歉我的英語。 – cabita

+0

對不起,看不懂。如果你只是想打印這個變量(你爲什麼要從控制器來做這件事?),只需要echo $ this-> variable;還是你得到臭名昭着的Codeigniter死亡白屏? – Rooneyl

+0

@cabita如果你想給我發送你的代碼,我會看看它併發回(希望工作) – Rooneyl

4

您需要定義一個參數myOtherFunction,然後簡單地從myFunction()傳遞值:

function myFunction(){ 
    $variable = 'hello'; 
    $this->myOtherFunction($variable); 
} 

function myOtherFunction($variable){ 
    // $variable passed from myFunction() is equal to 'hello'; 
} 
+0

你好。我把下面的代碼: function myfn1(){ $ variable ='hola'; $ this-> myfn2($ variable); } function myfn2($ variable){ echo $ variable; } 和我出現下一個錯誤: 甲PHP錯誤遇到 嚴重性:警告 消息:缺少參數1 testdropdown :: myfn2() 文件名:控制器/ testdropdown.php 行號:20 甲PHP錯誤遇到 嚴重性:注意 消息:未定義變量:變量 文件名:控制器/ testdropdown.php 行號:22 感謝您的幫助。 – cabita

相關問題