1

Lets say i have the following code.

class A {
    function one() {
        return $this;
    }
}

class B extends A {
    function two() {
        return $this;
    }
}

Is there any way possible that i can method chain using a function from the parent class? Such as..

$b = new B();
$b->one()->two();
cnotethegr8
  • 7,342
  • 8
  • 68
  • 104
  • 3
    What's wrong with it? It works for me Add some echo's in there and you will see the output in the correct order. – Gohn67 Apr 21 '12 at 17:56
  • @Gohn67 - Your right,.. so in my real method there must be something else wrong, the page keeps crashing. I guess i should of tested out this simplified version first. :) thanks! – cnotethegr8 Apr 21 '12 at 18:22

1 Answers1

0

Refer to this question for several responses that explain the meaning of the special variable $this.

In short, it refers to the current object. You're creating an instance of B, so even if you refer to $this within function one() you're still referring to the enclosing instance.

Community
  • 1
  • 1
AJ.
  • 27,586
  • 18
  • 84
  • 94
  • B inherits from A, so I think his code example actually works. – Gohn67 Apr 21 '12 at 17:57
  • Yes, the code does execute. I didn't say the code doesn't work. I just said that `$this` is going to refer to the instance of `B` in both cases. – AJ. Apr 21 '12 at 17:59