- print_r: documentation ( source)
- json_encode: documentation ( source)
<?php
class Config implements ArrayAccess, Countable
{
/**
* @var ArrayObject
*/
private $storage;
/**
* @param array $preset
*/
public function __construct($preset)
{
$this->storage = new ArrayObject($preset);
$this->storage->setFlags(
ArrayObject::STD_PROP_LIST | ArrayObject::ARRAY_AS_PROPS
);
}
/**
* ArrayAccess offsetGet (getter).
*
* @param string $index
*/
public function offsetGet($index)
{
return isset($this->storage->{$index}) ? $this->storage->{$index} : null;
}
/**
* ArrayAccess offsetSet (setter).
*
* @param string $index
* @param mixed $value
*/
public function offsetSet($index, $value)
{
if (is_null($index)) {
$this->storage[] = $value;
} else {
$this->storage->{$index} = $value;
}
}
/**
* ArrayAccess offsetExists (isset).
*
* @param string $index
*/
public function offsetExists($index)
{
return isset($this->storage->{$index});
}
/**
* ArrayAccess offsetUnset (unset).
*
* @param string $index
*/
public function offsetUnset($index)
{
unset($this->storage->{$index});
}
/**
* Magic method (getter).
*
* @param string $index
*/
public function __get($index)
{
return $this->offsetGet($index);
}
/**
* Magic method (setter).
*
* @param string $index
* @param mixed $value
*/
public function __set($index, $value)
{
return $this->offsetSet($index, $value);
}
/**
* Magic method (isset).
*
* @param string $index
*/
public function __isset($index)
{
return $this->offsetExists($index);
}
/**
* Magic method (unset).
*
* @param string $index
*/
public function __unset($index)
{
return $this->offsetUnset($index);
}
/**
* Magic method (as function invoker).
*
* @param mixed $arguments
*/
public function __invoke(...$arguments)
{
if (isset($this->storage->{$arguments[0]})) {
return $this->storage->{$arguments[0]};
}
}
/**
* Magic method (toString well json).
*/
public function __toString()
{
$return = [];
foreach ($this->storage as $key => $value) {
$return[$key] = $value;
}
return json_encode($return, JSON_PRETTY_PRINT);
}
/**
* Magic method (override print_r/var_dump).
*/
public function __debugInfo()
{
$return = [];
foreach ($this->storage as $key => $value) {
$return[$key] = $value;
}
return $return;
}
/**
* Implements Countable
*/
public function count()
{
return $this->storage->count();
}
}
$config = new Config([
'url' => 'https://example.com',
'title' => 'My dynamic website'
]);
echo $config->url.PHP_EOL;
echo $config['title'].PHP_EOL;
echo count($config).PHP_EOL;
echo print_r($config, true).PHP_EOL;
echo $config.PHP_EOL;