Static Methods and $this in OOP in PHP
Inside static methods, $this is not available.
This happens because static methods
can be called outside the object context,
simply by referring to the class name.
In regular methods, both static and regular properties and methods are available.
Let's look at examples. Example for a regular method:
<?php
class Test
{
public static $staticProperty = 'static';
public $usualProperty = 'usual';
public function method()
{
echo self::$staticProperty; // will output 'static'
echo $this->usualProperty; // will output 'usual'
}
}
$test = new Test;
$test->method();
?>
Example for a static method:
<?php
class Test
{
public static $staticProperty = 'static';
public $usualProperty = 'usual';
public static function method()
{
echo self::$staticProperty; // will output 'static'
echo $this->usualProperty; // will throw an error
}
}
$test = new Test;
$test::method();
?>