Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Keyword protected

A protected member can be used inside its class and related classes in its inheritance hierarchy.

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

Syntax

protected int $units = 2;

A protected member can be used inside its class and related classes in its inheritance hierarchy. Child methods can manipulate an inherited protected field, while direct outside access without a magic handler raises Error. PHP 8.4 also permits a separate protected(set) visibility for typed properties.

class Base {protected int $units=2;}
class Child extends Base {public function take():int{return --$this->units;}}
$c=new Child(); echo $c->take(); try {echo $c->units;} catch(Error $e){echo " ",get_class($e);}
1 Error

Examples

<?php
class Base {protected int $units=2;}
class Child extends Base {public function take():int{return --$this->units;}}
$c=new Child(); echo $c->take(); try {echo $c->units;} catch(Error $e){echo " ",get_class($e);}

Result

1 Error

Sources