2012-05-23 11:50:20 -04:00
|
|
|
<?php
|
|
|
|
/**
|
|
|
|
* JSObject
|
|
|
|
*
|
|
|
|
* A PHP class to have an analoge to javascript's object literals
|
|
|
|
*
|
|
|
|
* @package JSObject
|
|
|
|
* @author Timothy J. Warren
|
|
|
|
* @copyright Copyright (c) 2012
|
|
|
|
* @link https://github.com/aviat4ion/JSObject
|
|
|
|
*/
|
|
|
|
|
|
|
|
// --------------------------------------------------------------------------
|
|
|
|
|
|
|
|
/**
|
|
|
|
* JSObject class
|
|
|
|
*
|
|
|
|
* @package JSObject
|
|
|
|
*/
|
2012-05-23 15:52:49 -04:00
|
|
|
class JSObject extends ArrayObject {
|
2012-05-23 11:50:20 -04:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Create the object
|
|
|
|
*
|
|
|
|
* @param mixed
|
|
|
|
*/
|
|
|
|
public function __construct($params = [])
|
|
|
|
{
|
2012-05-23 15:52:49 -04:00
|
|
|
parent::__construct($params, ArrayObject::ARRAY_AS_PROPS);
|
|
|
|
|
2012-05-23 11:50:20 -04:00
|
|
|
foreach($params as $name => &$val)
|
|
|
|
{
|
|
|
|
// Bind '$this' for closures
|
|
|
|
if ($val instanceof Closure)
|
|
|
|
{
|
2012-05-23 15:52:49 -04:00
|
|
|
$val = $val->bindTo($this);
|
2012-05-23 11:50:20 -04:00
|
|
|
}
|
2012-05-23 15:52:49 -04:00
|
|
|
|
2012-05-23 11:50:20 -04:00
|
|
|
// Add the parameter to the object
|
|
|
|
$this->$name = $val;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2012-05-23 15:52:49 -04:00
|
|
|
// --------------------------------------------------------------------------
|
|
|
|
|
2012-05-23 11:50:20 -04:00
|
|
|
/**
|
|
|
|
* Magic method to invoke appended closures
|
|
|
|
*
|
|
|
|
* @param string
|
|
|
|
* @param array
|
|
|
|
* @return mixed
|
|
|
|
*/
|
|
|
|
public function __call($name, $params = [])
|
|
|
|
{
|
2012-05-23 15:52:49 -04:00
|
|
|
// Allow array operations on the object
|
|
|
|
if (substr($name, 0, 6) === 'array_' && is_callable($name))
|
|
|
|
{
|
|
|
|
$args = array_merge($this->getArrayCopy(), $params);
|
|
|
|
return call_user_func_array($name, [$args]);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Call closures attached to the object
|
2012-05-23 11:50:20 -04:00
|
|
|
if (is_callable($this->$name))
|
|
|
|
{
|
|
|
|
return call_user_func_array($this->$name, $params);
|
|
|
|
}
|
|
|
|
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// End of JSObject.php
|