Nicholas Summers
Nicholas Summers

Reputation: 4756

Creating referenced keys within an array in PHP

At the moment, my script creates referenced keys this:

<?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;

My question is: there a better way to do this, possibly all in one go?

I know the below code doesn't work, but perhaps someone knows a better way?

<?php
$arr = array(
  'a' => '1',
  'b' => &$arr['a']
);

Upvotes: 4

Views: 51

Answers (1)

scrowler
scrowler

Reputation: 24405

I need to recreate the array without making a reference to the original object

You should use object cloning, which was introduced in PHP5. This will allow you to make a copy of your object with the current values, while allowing the original class to maintain any references to other variables already in place:

$arr = clone $this->object;

Variables will be accessible as class properties rather than array keys as in your example. If there's a problem with that for you, you could use something like get_class_vars() to return an array of the properties of your class.

Upvotes: 2

Related Questions