class Registry
{
protected static $instance = NULL;
protected $registry = array();
private function __construct()
{
// 没有人可以创建这个类的实例
}
public static function getInstance()
{
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public function __get($key)
{
return $this->registry[$key] ?? NULL;
}
public function __set($key, $value)
{
$this->registry[$key] = $value;
}
}
class Test
{
public const TEST_WHOLE_WORLD = 'visible.everywhere';
// NOTE: 只能在 PHP 7.1及以上版本中工作
protected const TEST_INHERITED = 'visible.in.child.classes';
// NOTE: 只能在 PHP 7.1及以上版本中工作
private const TEST_LOCAL= 'local.to.class.Test.only';
public static function getTestInherited()
{
return static::TEST_INHERITED;
}
public static function getTestLocal()
{
return static::TEST_LOCAL;
}
}
$base = new Base();
$customer = new Customer();
$customer->setId();
$customer->setName('Test');
echo 'Welcome ' . $customer->getName() . PHP_EOL;
echo 'Your new ID number is: ' . $customer->getId() . PHP_EOL;
echo 'Key (does not work): ' . $base->key;
echo 'Key (does not work): ' . $customer->key;
echo 'Name (does not work): ' . $customer->name;
echo 'Random ID (does not work): ' . $customer->generateRandId();