Recent Posts

Showing posts with label $this. Show all posts
Showing posts with label $this. Show all posts

PHP 5: When to use $self or $this

From http://www.phpbuilder.com/board/showthread.php?t=10354489:

Use $this to refer to the current object. Use self to refer to the current class. In other words, use$this->member for non-static members, use self::$member for static members.


How to solve: Fatal error: Using $this when not in object context

$this is a special variable in PHP which can not be assigned. If it is accessed in a context where it does not exist, this fatal error is given.
This error can occur:
  1. If a non-static method is called statically. Example:
    class Foo {
       protected $var;
       public function __construct($var) {
           $this->var = $var;
       }
    
       public static function bar () {
           // ^^^^^^
           echo $this->var;
           //   ^^^^^
       }
    }
    
    Foo::bar();
    How to fix: review your code again, $this could only used in object context, and should never in a static method. And also, static method should not access the non-static property. Use self::$static_property to access the static property.
  2. If code from a class method has been copied over into a normal function or just the global scopeand keeping the $this special variable.
    How to fix: Review the code and replace $this with a different substitution variable.