目前,我的脚本创建了引用的键:
<?php
$arr = array(
'authority' => $this->object->authority,
'fragment' => $this->object->fragment,
'host' => $this->object->host,
'pass' => $this->object->pass,
'path' => $this->object->path,
'port' => $this->object->port,
'query' => $this->object->query,
'scheme' => $this->object->scheme,
'scheme_name' => $this->object->scheme_name,
'scheme_symbols' => $this->object->scheme_symbols,
'user' => $this->object->user,
);
$arr['domain'] = &$arr['host'];
$arr['fqdn'] = &$arr['host'];
$arr['password'] = &$arr['pass'];
$arr['protocol'] = &$arr['scheme'];
$arr['username'] = &$arr['user'];
ksort($arr);
return $arr;
我的问题是:有更好的方法来做到这一点,可能一气呵成吗?
我知道下面的代码不起作用,但也许有人知道更好的方法吗?
<?php
$arr = array(
'a' => '1',
'b' => &$arr['a']
);
最佳答案
I need to recreate the array without making a reference to the original object
你应该使用在PHP5中引入的object cloning.这将允许您使用当前值创建对象的副本,同时允许原始类维护对已经存在的其他变量的任何引用:
$arr = clone $this->object;
变量可以作为类属性访问,而不是像示例中的数组键一样.如果您遇到问题,可以使用类似于get_class_vars()
的内容返回类的属性数组.