4

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']
);
8
  • Firstly, What exactly do you want the code to do? And why?. We need background to be able to offer a solution. Commented Jul 24, 2014 at 2:34
  • Pass a key by reference the first example gets the job done, but I am asking if there is a better way. This all comes from a much larger class where having these passed by reference is important. Commented Jul 24, 2014 at 2:37
  • Are you asking how to shorten this code? If so, could you use a function like get_class_vars() to get an array of all public properties of your class, then assign your array based on those? Commented Jul 24, 2014 at 2:39
  • @NickJ I rolled back to your original post since you say that having the variables passed by reference is important. Commented Jul 24, 2014 at 2:40
  • Sorry that's not an option, I need to recreate the array without making a reference to the original object. In short, I can't just copy the original object because of pre-existing references. Commented Jul 24, 2014 at 2:45

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.