开发者

To pass value of a variable in one function to another function in same class

开发者 https://www.devze.com 2023-03-12 03:16 出处:网络
I have a class Block_Model (actually a model in Kohana framework) with 2 methods input()and output().

I have a class Block_Model (actually a model in Kohana framework) with 2 methods input()and output().

class Block_Model extends ORM {
    function input($arg) {
        //...
    }
    function output() {
        //...
    }
    //...
}

The method input is called from a function written inside a con开发者_开发百科troller called Home_Controller and it passes an argument to the method input.

class Home_Controller extends Controller {
    function doSomething() {
        $block = new Block_Model();
        //...
        $block->input($val);
        //...
    }
}

How can I make the argument passed to input() be accessible in the method output()?


You'll need private property:

class Something{
   private $_variable = "";

   function input( $data ){
      $this->_variable = $data;
      //do the rest of function
   }

   function output(  ){
      //get previously set data
      echo $this->_variable;
   }

}


This is similar to @silent's answer, but you can combine setter & getter in one method.

protected $_foo;

public function foo($val = NULL)
{
    if ($val === NULL)
    {
        // its a getter!
        return $this->_foo;
    }

    // its a setter 
    $this->_foo = $val;
    // return current object, so it becomes a chainable method
    return $this;
}

Now you can use $value = $object->foo(); and $object->foo($value)->do_something_else();

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号