Skip to content

Instantly share code, notes, and snippets.

@dg dg/StrictObject.php
Created Jun 11, 2018

Embed
What would you like to do?
Nette\StrictObject, simplified alternative for Nette\SmartObject (compatible with nette/utils 2.4)
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette;
use Nette\Utils\ObjectHelpers;
/**
* Strict class for better experience.
* - 'did you mean' hints
* - access to undeclared members throws exceptions
*/
trait StrictObject
{
/**
* @return mixed
* @throws MemberAccessException
*/
public function __call($name, $args)
{
ObjectHelpers::strictCall(get_class($this), $name);
}
/**
* @return void
* @throws MemberAccessException
*/
public static function __callStatic($name, $args)
{
ObjectHelpers::strictStaticCall(get_called_class(), $name);
}
/**
* @return mixed property value
* @throws MemberAccessException if the property is not defined.
*/
public function & __get($name)
{
ObjectHelpers::strictGet(get_class($this), $name);
}
/**
* @return void
* @throws MemberAccessException if the property is not defined or is read-only
*/
public function __set($name, $value)
{
$class = get_class($this);
if (ObjectHelpers::hasProperty($class, $name)) { // unsetted property
$this->$name = $value;
} else {
ObjectHelpers::strictSet($class, $name);
}
}
/**
* @return void
* @throws MemberAccessException
*/
public function __unset($name)
{
$class = get_class($this);
if (!ObjectHelpers::hasProperty($class, $name)) {
throw new MemberAccessException("Cannot unset the property $class::\$$name.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.