KennisbankExamencentrum
NL · NLNederlands (Nederland)
Taal kiezen13

CKTIS / PHP

Magische methoden

Magische methoden koppelen taalbewerkingen aan een object.

Versie: PHP 8.4; repository runtime, production runtime not attested

Syntax

public function __get(string $name): mixed; public function __isset(string $name): bool;

Magische methoden koppelen taalbewerkingen aan een object. Een ontoegankelijke eigenschap lezen kan __get() aanroepen, isset() vraagt een aanwezige __isset(). Behandel ontbreken en null consistent. Gewone toegang tot een geïnitialiseerd publiek veld omzeilt deze methoden.

class Bag{public string $label="box";private array $data=["qty"=>0,"memo"=>null];public function __get(string $k):mixed{return $this->data[$k]??null;}public function __isset(string $k):bool{return isset($this->data[$k]);}}
$b=new Bag();echo json_encode([$b->label,$b->qty,isset($b->qty),isset($b->memo),$b->missing]);
["box",0,true,false,null]

Voorbeelden

<?php
class Bag{public string $label="box";private array $data=["qty"=>0,"memo"=>null];public function __get(string $k):mixed{return $this->data[$k]??null;}public function __isset(string $k):bool{return isset($this->data[$k]);}}
$b=new Bag();echo json_encode([$b->label,$b->qty,isset($b->qty),isset($b->memo),$b->missing]);

Resultaat

["box",0,true,false,null]

Bronnen