-1

How can I have a class which allows me to have a another variable when calling,

eg.

$class->variable1->variable2->function();
jh314
  • 27,144
  • 16
  • 62
  • 82
Imque
  • 7
  • 1
  • I think variable1 and variable2 are going to have to be objects, and the class of variable two must contain a funcion() method – user1020317 Aug 09 '13 at 15:01
  • Are you asking about this because you think it's cool or because you actually have a need for it? Are you familiar with object oriented programming at all? – N.B. Aug 09 '13 at 15:11
  • I have a neeed for it, I do know a little about OOP – Imque Aug 09 '13 at 15:14

2 Answers2

2

If you wanted say $class->function1()->function2()->function3(), you would need to return $this at the end of your function logic.

As for $class->var->var->func() you would need to have the $class->var->var as a new instance of the class the function belongs to.

Bojangles
  • 99,427
  • 50
  • 170
  • 208
appnus
  • 101
  • 5
2

This is what you think of:

class OtherClass {
  public function something() {
    return "foo";
  }
}

class Test {
  public $variable;
  public function Test() {
    $this->variable = new OtherClass();
  }
}

$foo = new Test();
echo $foo->variable->something();

But if you want that kind of method chaining is questionable. You probably want to look into http://php.net/oop for a complete reference on Object Oriented Programming with PHP.

fdomig
  • 4,417
  • 3
  • 26
  • 39
  • I corrected a typo, it should work now. Sorry. – fdomig Aug 09 '13 at 15:13
  • 1
    @Imque - if a suggested piece of code doesn't work, then it is your job to try experimenting and doing some debugging. If your report simply says "doesn't work", then (a) you may attract downvotes for not making an effort, and (b) the person who has helped you has been given no extra information with which to assist you. Be as detailed as you can, then, when supplying feedback. – halfer Aug 19 '13 at 22:31