Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Magic methods

Magic methods connect language operations to an object.

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

Syntax

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

Magic methods connect language operations to an object. Reading an inaccessible property can invoke __get(), whereas isset() asks __isset() when available. Implement coherent behavior for missing and null values. Normal access to a public initialized property bypasses these hooks.

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]

Examples

<?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]);

Result

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

Sources