简体   繁体   English

PHP将数组传递给类

[英]PHP passing array to class

I have a array with about 300 indexes and each index has about 8 "sub-indexes"(?). 我有大约300个索引的数组,每个索引都有大约8个“子索引”(?)。 So it is a large(ish) array. 因此,这是一个很大的数组。 I am working on converting my code to oop style and one of my classes(colors) will need this array passed as an argument. 我正在将代码转换为oop样式,我的一个类(颜色)将需要将此数组作为参数传递。 So my question is simple....if I create 100 color classes and pass each the array I am not creating 100 separate arrays correct just 100 pointers? 所以我的问题很简单....如果我创建100个颜色类并传递每个数组,我不是在创建100个单独的数组,而只是校正100个指针?

$colors['Apricot'] = array(250,180,160,3341,328,826,194,3332,0);
$colors['Apricot, Light'] = array(255,230,225,3824,8,833,2605,-1,1);

$x=new color();
$y=new color();
$z=new color();

$x->doSomething($colors);
$y->doSomething($colors);
$z->doSomething($colors);

Thee is still only one copy of the array, not three? 您仍然只是数组的一个副本,而不是三个?

Thank you, Todd 谢谢托德

True. 真正。 But in theory the array is copied as value . 但是从理论上讲,数组是作为值复制的 It's just that PHP-internally it will not be duplicated in memory ... unless one of your objects starts to modify that passed array. 只是在PHP内部,它不会在内存中重复 ...除非您的对象之一开始修改该传递的数组。

In which case you could pass an explicit & reference rather, or even convert it into an ArrayObject prior. 在这种情况下,您可以传递一个显式&引用,甚至可以先将其转换为ArrayObject。 (Again: practically unnecessary if you don't plan on editing the array.) (再次:如果您不打算编辑数组,则几乎是不必要的。)

Yes, you are creating 100 copies, because scalar and array arguments are, by default, passed by value, and not by reference, to class methods in PHP. 是的,您正在创建100个副本,因为默认情况下,标量和数组参数是按值而不是按引用传递给PHP中的类方法的。

In order for the method to take in the argument by reference you'd have to change the method signature by prepending an ampersand to the parameter name, like so: 为了使方法通过引用接受参数,您必须通过在参数名称前加上“&”号来更改方法签名,如下所示:

public function doSomething( &$argument )
{
}

edit: 编辑:
For a more accurate account of the internal workings, please see mario's answer . 要更准确地说明内部工作原理,请参阅mario的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM