PHP 可以使用同一数组中的值来初始化数组吗?

发布于 2024-11-26 11:06:38 字数 294 浏览 2 评论 0原文

我想将当前路径信息保存在数组中,并且一个字段是另一个字段的一部分。我可以在初始化期间访问同一数组的字段吗?

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

还是我必须一一签上姓名首字母?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

嘿看小鸭子会跑 2024-12-03 11:06:38

当您定义数组时,该数组仍然是未定义的。但是,您可以定义其他(临时)变量来动态执行此操作:

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

但是通常不需要这样做,因为您在数组中复制数据。只是说,你可以做任何你想做的事:)

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 :)

远昼 2024-12-03 11:06:38

你必须一一初始化它们。

最好将array视为构造函数。在函数调用完成之前,数组本身并不完全存在,并且在大多数情况下您无法访问不完全存在的内容。

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.

甜心 2024-12-03 11:06:38

是的,你必须一一初始化,因为 $this->path 在 array() 函数完成后被填充。

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

披肩女神 2024-12-03 11:06:38

据我所知,您尝试做的任务不是一项功能性任务。

代码:

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

...呈现以下内容:

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

由于数组是一次性创建的,而不是每个元素创建一次,因此它将无法在与赋值相同的语句中引用值。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文