1

I want to save current path information in an Array and one field is a part of another. Can I access a field of the same array during initialization?

$this->path = array
(
     'rel_image' => '/images',
     'document_path' => '/a/file/path',
     'path' => $this->path['document_path'].$this->path['rel_images']
);

or do I have to initial them one by one?

4 Answers 4

2

The array still is undefined while you're defining it. However you can define other (temporary) variables to do so on the fly:

$this->path = array
(
     'rel_image' => $r = '/images',
     'document_path' => $p = '/a/file/path',
     'path' => $p.$r
);

However that normally should not be needed, as you're duplicating data within the array. Just saying, you can do whatever you want :)

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

Comments

1

You have to initialize them one by one.

It is best to think of array as a constructor. The array itself doesn't completely exist until after the function call is complete, and you can't access something which doesn't completely exist in most circumstances.

2 Comments

Function call? Of the constructor?
Well, array is a function which returns an array. But it is like a constructor in that it returns an initialized object. But it is... array is special.
0

yes, you have to initialize one by one, beacuse $this->path is being filled after array() function is done.

Comments

0

As far as I know, the assignment you're trying to do isn't a functional one.

Code:

 <?php $array = array('foo' => 'bar', 'bar' => $array['foo']); ?>
 <pre><?php print_r($array); ?></pre>

...renders the following:

Array
(
    [foo] => bar
    [bar] => 
)

As the array is created at one time, not once per element, it will not be able to reference the values in the same statement as the assignment.

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.