Last active
December 10, 2015 20:59
-
-
Save CHH/4492282 to your computer and use it in GitHub Desktop.
A simple struct class for PHP.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
abstract class Struct implements \ArrayAccess | |
{ | |
function __construct($properties = array()) | |
{ | |
$this->init(); | |
foreach ($properties as $property => $value) { | |
$this->$property = $value; | |
} | |
} | |
function init() | |
{} | |
function offsetGet($offset) | |
{ | |
return $this->$offset; | |
} | |
function offsetSet($offset, $value) | |
{ | |
$this->$offset = $value; | |
} | |
function offsetExists($offset) | |
{ | |
return isset($this->$offset); | |
} | |
function offsetUnset($offset) | |
{ | |
unset($this->$offset); | |
} | |
final function __get($property) | |
{ | |
throw new \RuntimeException(sprintf('Undefined field "%s"', $property)); | |
} | |
final function __set($property, $value) | |
{ | |
throw new \RuntimeException(sprintf('Undefined field "%s"', $property)); | |
} | |
} | |
# Defining structs works like defining a class, and the fields are its public members. | |
class Pathinfo extends Struct | |
{ | |
var $dirname; | |
var $basename; | |
var $extension; | |
var $filename; | |
# Structs can also implement an "init" method, which can initialize | |
# fields with complex values (like objects) | |
# | |
# function init() { | |
# } | |
} | |
# Structs feature a default constructor which takes an array | |
# and assigns the keys as properties. | |
$i = new Pathinfo([ | |
'dirname' => '/foo', 'basename' => 'bar.php', 'extension' => 'php' | |
]); | |
# Fields can be accessed either via brackets or as object member. | |
printf("Basename: %s\n", $i["basename"]); | |
printf("Dirname: %s\n", $i->dirname); | |
# Trying to access undefined fields causes an Exception | |
try { | |
$i['foo']; | |
} catch (\RuntimeException $e) { | |
echo $e->getMessage(), "\n"; | |
} |
Went looking on Packagist for this today, so I suppose my answer is "yes, this would be sufficient".
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please tell me in comments if this would be sufficient as Struct class for PHP. If yes then I will work on releasing this as a small library.