如何从同一个类的不同函数中访问变量?

时间:2013-06-07 09:43:36

标签: php codeigniter class variables global-variables

控制器:

function act() {
    //some code for connection
    $input = (response from client);
    return $input;
}

这是第一次调用该行为以连接到客户端。 在这里,我将通过连接获得输入变量。

function a() {
    $a = $this->act();  
}

如果不再重新建立连接,我如何获得此功能中的$input

function b() {

}

我已尝试将会话设为flashdata,但它无效。

4 个答案:

答案 0 :(得分:3)

你不能。

为了获得该变量,您需要将其置于函数本身之外。

class MyController extends CI_Controller
{
    private $variable;

    private function act()
    {
        $input = (response from client)
        return $input
    }

    private function a()
    {
        $this->variable = $this->act();
    }
}

这样做可以让您从班级中的任何地方访问变量 希望这会有所帮助。

答案 1 :(得分:2)

class中简单定义一个像

这样的变量
 in controller class below function is written. 
Class myclass {
public  $_customvariable;

function act(){
   //some code for connection
 $this->_customvariable=  $input = (response from client);
   return $input;
}

function a() {
$a = $this->act();  
}
function b(){
 echo $this->_customvariable;//contains the $input value 
    }

 }

答案 2 :(得分:0)

class fooBar {

    private $connection;

    public function __construct() {
        $this->act();
    }

    public function act(){
       //some code for connection
       $this->connection = (response from client);
    }

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

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

答案 3 :(得分:0)

你可以在方法或函数中使用静态变量,响应在函数中被“缓存”

function act(){
    static $input;
    if (empty($input))
    {
        //some code for connection
        $input = (response from client);
    }
    return $input;
}
相关问题