Metode statice și $this în OOP în PHP
În interiorul metodelor statice nu este accesibil $this.
Acest lucru se întâmplă deoarece metodele statice
pot fi apelate în afara contextului obiectului,
accesând pur și simplu numele clasei.
În metodele obișnuite sunt accesibile atât proprietățile și metodele statice, cât și cele obișnuite.
Să ne uităm la exemple. Exemplu pentru metodă obișnuită:
<?php
class Test
{
public static $staticProperty = 'static';
public $usualProperty = 'usual';
public function method()
{
echo self::$staticProperty; // va afișa 'static'
echo $this->usualProperty; // va afișa 'usual'
}
}
$test = new Test;
$test->method();
?>
Exemplu pentru metodă statică:
<?php
class Test
{
public static $staticProperty = 'static';
public $usualProperty = 'usual';
public static function method()
{
echo self::$staticProperty; // va afișa 'static'
echo $this->usualProperty; // va genera o eroare
}
}
$test = new Test;
$test::method();
?>