Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scope of $this is funked in PHP is it a bug or a feature?

Tags:

oop

php

I have this code:

    class a(){
      function b(){
         if(isset($this){
            echo 'instance! ';
            echo get_class($this);
         }else{
            echo 'static';
         }
      }
    }


class C{
  public function test(){
      a::b();
  }
}

$CC=new C;
$CC->test();

This will echo

instance C

like image 442
Itay Moav -Malimovka Avatar asked Sep 24 '11 14:09

Itay Moav -Malimovka


People also ask

What is return $this in PHP?

$this means the current object, the one the method is currently being run on. By returning $this a reference to the object the method is working gets sent back to the calling function.

What does $$$ mean in PHP?

PHP $ and $$ Variables. The $var (single dollar) is a normal variable with the name var that stores any value like string, integer, float, etc. The $$var (double dollar) is a reference variable that stores the value of the $variable inside it.


1 Answers

The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).

source

So definitely, it's a feature, it's by design, and it's not a bug.

like image 192
Maxim Krizhanovsky Avatar answered Nov 14 '22 23:11

Maxim Krizhanovsky