Statiska metoder och $this i OOP i PHP
Inuti statiska metoder är $this inte tillgänglig.
Detta beror på att statiska metoder
kan anropas utanför ett objekts kontext,
genom att helt enkelt referera till klassens namn.
I vanliga metoder är både statiska och vanliga egenskaper och metoder tillgängliga.
Låt oss titta på exempel. Exempel på en vanlig metod:
<?php
class Test
{
public static $staticProperty = 'static';
public $usualProperty = 'usual';
public function method()
{
echo self::$staticProperty; // skriver ut 'static'
echo $this->usualProperty; // skriver ut 'usual'
}
}
$test = new Test;
$test->method();
?>
Exempel på en statisk metod:
<?php
class Test
{
public static $staticProperty = 'static';
public $usualProperty = 'usual';
public static function method()
{
echo self::$staticProperty; // skriver ut 'static'
echo $this->usualProperty; // kommer att ge ett fel
}
}
$test = new Test;
$test::method();
?>