我们有很多现有的代码,它们不会创建一个类的实例,也不会在该类上使用静态函数,而是会在该类的全局单例上调用该方法。
例如(stringclass.php):
class String {
function endsWith($str, $search) {
return substr($str, -strlen($search)) == $search;
}
}
$STRING_OBJECT = new String();
那么它将以以下方式使用它:
include_once("stringclass.php");
if ($STRING_OBJECT->endsWith("Something", "thing")) {
echo "It's there'n";
}
我意识到这不是一种非常明智的调用函数的方式,但我想知道我们是否可以在不更改所有使用这些singleton的代码的情况下,修复人们忘记使用自动加载器包含正确类的所有地方。它将检测未声明的全局的使用,并根据被引用的全局的名称包含正确的类文件。
您可以使用ArrayAccess接口
http://php.net/manual/en/class.arrayaccess.php
class Ztring implements arrayaccess
{
private $container = array ();
public function offsetSet ($offset, $value)
{
$this->container[$offset] = $value;
}
public function offsetGet ($offset)
{
// exception
if ($offset == 'something')
{
return 'works!';
}
return $this->container[$offset];
}
public function offsetExists ($offset)
{
return isset($this->container[$offset]);
}
public function offsetUnset ($offset)
{
unset ($this->container[$offset]);
}
}
$x = new Ztring ();
$x['zzz'] = 'whatever';
echo $x['zzz']."'n";
echo $x['something']."'n";