Statiske metoder og $this i OOP i PHP
Inden for statiske metoder er $this ikke tilgængelig.
Dette skyldes, at statiske metoder
kan kaldes uden for en objekts kontekst
ved blot at henvise til klassens navn.
I almindelige metoder er både statiske og almindelige egenskaber og metoder tilgængelige.
Lad os se på eksempler. Eksempel på en almindelig metode:
<?php
class Test
{
public static $staticProperty = 'static';
public $usualProperty = 'usual';
public function method()
{
echo self::$staticProperty; // vil udskrive 'static'
echo $this->usualProperty; // vil udskrive 'usual'
}
}
$test = new Test;
$test->method();
?>
Eksempel på en statisk metode:
<?php
class Test
{
public static $staticProperty = 'static';
public $usualProperty = 'usual';
public static function method()
{
echo self::$staticProperty; // vil udskrive 'static'
echo $this->usualProperty; // vil give en fejl
}
}
$test = new Test;
$test::method();
?>