oop - $this and instantiating classes in PHP -


i'm having hard time understanding pseudo variable $this. take example following code:

<?php class {     function foo()     {         if (isset($this)) {             echo '$this defined (';             echo get_class($this);             echo ")\n";         } else {             echo "\$this not defined.\n";         }     } }  $a = new a(); $a->foo(); a::foo(); ?> 

it output:

$this defined (a) $this not defined. 

ok, output makes sense me, since $a->foo refers instance , a::foo refers class without instantiation. take other example, if append following code first example:

<?php class b {     function bar()     {         a::foo();     } }  $b = new b(); $b->bar(); b::bar(); ?> 

it output this:

$this defined (b) $this not defined. 

i can understand second output, because b::bar(); refers class, not instance. don't first output. why $this instantiated if method calls a::foo();, class , should not instantiated, , worse, why $this instance of b , not of a?

thanks attention!

by instantiating b setting $this instance of b.

since a::foo() echoes $this if it's defined (which since calling a::foo() inside instance of b) see a::foo() echoing b instance.

$b = new b() // member function of b has $this defined now.  $b->bar() // member function of b, $this defined. a::foo() echo b's instance of $this  a::foo() // no class instantiation, $this not defined  b::bar() // no class instantiated, $this not defined pointed out earlier. 

Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -