__get() magic method is a lot powerful and let us get things done within classes with more ease.

First Example


class User
{
	protected $data = [
		'email'=> '[email protected]'
	];

	public function __get($key){
		return $this->data[$key] ?? null;
	}
}

$user = new User();

var_dump($user->email);

In this example, we’ve defined a set of Data collection within the User class which we’d like to get using __get() magic method.

Notice that if we try to get another property from the class, lets say $user->first_name; It will output NULL.

Another Example (Creating Attribute Getters)

class User
{

	protected $data = [
		'first_name'=> 'usama',
		'last_name'=>'munir'
	];


	public function __get($key){
		return $this->data[$key] ?? null;
	}

	public function fullName(){
		return trim($this->first_name . ' ' . $this->last_name);
	}

}

$user = new User();

var_dump($user->fullName());

If you notice here, after defining our __get() magic method, we’re internally referencing $this->first_name and $this->last_name properties.

Another Example (Getting Attributes)

class User
{

	protected $data = [
		'first_name'=> 'usama',
		'last_name'=>'munir'
	];

	public function __get($key){
		if(method_exists($this, $method = 'get' . ucfirst($key) . 'Attribute')){
			return $this->{$method}();
		}

		return $this->data[$key] ?? null;
	}

	public function getFullNameAttribute(){
		return trim($this->first_name . ' ' . $this->last_name);
	}

}
 
$user = new User();

var_dump($user->fullName);

In this example, we’ve tried to achieve Laravel style getters of Attributes and calling them directly instead of calling functions. Notice how powerful this __get() magic method is.

Another Example (Data Presenter as Attributes)


class User
{

	protected $data = [
		'first_name'=> 'usama',
		'last_name'=>'munir'
	];

	public function __get($key){
		return $this->data[$key] ?? null;
	}

}
abstract class Presenter
{
	public function __get($key){
		if(method_exists($this,$key)){
			return $this->{$key}();
		}
		return null;
	}
}

class UserPresenter extends Presenter
{
	protected $user;

	public function __construct(User $user){
		$this->user = $user;
	}

	public function fullName(){
		return trim($this->user->first_name . ' ' . $this->user->last_name);
	}
}
 
$user = new User();
$presenter = new UserPresenter($user);
var_dump($presenter->fullName);

Presenter would allow us to get a list of methods available to use to present data to us and __get() magic method allows us to make use of it.

Here we’ve a couple of classes, User and UserPresenter and we’ve set the getter to use any of the functions in UserPresenter class to behave like properties just using __get() magic method.

You may also Like