Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

EbrahemSamer's avatar

what is the difference between __set(), __get(), __isset() and normal setter and getter ( PHP )?

If I wanna implement setter and getter on my private properties

Should I make it like this

class User {

private $Id;
private $username;

public function set($property, $value)
{
	$this->$property = $value;
}

public function get($property)
{
	return $this->$property;
}

public function isSet($property)
{
	return isset($this->$property);
}

}

Or using __set() , __get(), __isset()

and what is the difference if I achieve the same result ...

thanks

0 likes
1 reply
MichalOravec's avatar
Level 75

@ebrahemsamer They are Magic Methods

__set() is run when writing data to inaccessible (protected or private) or non-existing properties.

__get() is utilized for reading data from inaccessible (protected or private) or non-existing properties.

__isset() is triggered by calling isset() or empty() on inaccessible (protected or private) or non-existing properties.

__unset() is invoked when unset() is used on inaccessible (protected or private) or non-existing properties.

More information you can find here.

class User {
    private $Id;

    private $username;

    public function __get($property)
    {
        if (property_exists($this, $property)) {
            return $this->$property;
        }
    }

    public function __set($property, $value)
    {
        if (property_exists($this, $property)) {
            $this->$property = $value;
        }

        return $this;
    }
}

Please or to participate in this conversation.