Junior
Wat is het verschil tussen de sleutelwoorden self en this in PHP?
sobes.tech AI
Antwoord van AI
$this verwijst naar het huidige objectvoorbeeld. self verwijst naar de huidige klasse (in een statische context of binnen methoden om toegang te krijgen tot statische leden).
$this:
- Wordt gebruikt om toegang te krijgen tot de eigenschappen en methoden van een specifiek instantie van de klasse.
- Wordt toegepast binnen niet-statische methoden.
class MyClass {
public $instanceProperty = 'Hallo';
public function getInstanceProperty() {
// Toegang tot de eigenschap van de huidige instantie
return $this->instanceProperty;
}
}
self:
- Wordt gebruikt om toegang te krijgen tot de statische eigenschappen en methoden van de klasse.
- Wordt toegepast binnen zowel statische als niet-statische methoden.
class MyClass {
public static $staticProperty = 'Wereld';
public static function getStaticProperty() {
// Toegang tot de statische eigenschap
return self::$staticProperty;
}
public function accessStaticFromInstance() {
// Toegang tot de statische eigenschap vanuit een niet-statische methode
return self::$staticProperty;
}
}
Voorbeeld van het gebruik van $this en self samen:
class Example {
public $instanceId;
private static $count = 0;
public function __construct() {
// Gebruik van self om de statische teller te verhogen
self::$count++;
// Gebruik van $this om de instantie-eigenschap in te stellen
$this->instanceId = self::$count;
}
public static function getCount() {
// Gebruik van self om de statische eigenschap op te halen
return self::$count;
}
public function getInstanceId() {
// Gebruik van $this om de instantie-eigenschap op te halen
return $this->instanceId;
}
}