0

Possible Duplicate:
Get PHP class property by string
PHP method chaining?

I've got a class where a method returns the instance it's called on. How can I access a property (whose name is stored in a variable) directly from the return value of the function? Here's what I'm trying now:

class MyClass {
    public $variable_one;

    public function function_one() {
        $variable = 'last';
        // The problematic line: call method, access property on result
        return $this->function_two->$variable;
    }

    public function function_two($params = array()) {
        if (is_array($params)) {
            $params = http_build_query($params, NULL, '&');
        }

        $this->option(CURLOPT_COOKIE, $params);
        return $this;
    }
}
Community
  • 1
  • 1
  • What do you mean `$this->some_function->$variable`? – bfavaretto Jul 12 '12 at 03:07
  • Hi @bfavaretto i can't edited my question. Please see this http://pastebin.com/E0Rh8TpX –  Jul 12 '12 at 03:20
  • I think you're looking for method chaining. Please see the link above. – bfavaretto Jul 12 '12 at 03:25
  • your script contains some errors, the $variable is not set within the class only with method, you need define variable. but if you want to call function_two then returns local variable. then you can't use chaining. only if your variable defined within class scope then you can use chaining. also function_two lacks the parenthesis. – Dreaded semicolon Jul 12 '12 at 03:54

1 Answers1

0

The $this variable is special and only exists within classes. If you have a property within a class named variable, then you can access it with $this->variable from within that class.

class MyClass
{
   private $variable;
   public function getVariable()
   {
       return $this->variable;
   }
}
Lusitanian
  • 11,012
  • 1
  • 41
  • 38
  • I can't edited my question. Please see this http://pastebin.com/E0Rh8TpX –  Jul 12 '12 at 03:19