Skip to content

Instantly share code, notes, and snippets.

@CHH
Last active December 10, 2015 20:59
Show Gist options
  • Save CHH/4492282 to your computer and use it in GitHub Desktop.
Save CHH/4492282 to your computer and use it in GitHub Desktop.
A simple struct class for PHP.
<?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";
}
@CHH
Copy link
Author

CHH commented Jan 9, 2013

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.

@jwpage
Copy link

jwpage commented Jan 21, 2013

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