English 中文(简体)
PHP中(对Array的)目标变量
原标题:Object (into Array) variables in PHP

该守则是:

$obj = new stdClass;
$obj->AAA = "aaa";
$obj->BBB = "bbb";

$arr = array($obj, $obj);

print_r($arr);

$arr[1]->AAA = "bbb";
$arr[1]->BBB = "aaa";

print_r($arr);

这里的产出是:

Array
(
    [0] => stdClass Object
        (
            [AAA] => aaa
            [BBB] => bbb
        )

    [1] => stdClass Object
        (
            [AAA] => aaa
            [BBB] => bbb
        )

)

Array
(
    [0] => stdClass Object
        (
            [AAA] => bbb
            [BBB] => aaa
        )

    [1] => stdClass Object
        (
            [AAA] => bbb
            [BBB] => aaa
        )

)

没有人能够向我解释为什么所有物体变量(阵列)都发生变化?

并对我的坏官办公室感到担忧。 我不是一位当地艺术家。

最佳回答

该阵列储存了两处提及同一物体,而不是两个不同的物体,具体如下:

array(
    0 =>  ---|          stdClass
             |------->     [AAA] => bbb
    1 =>  ---|             [BBB] => aaa
)

如果你想要复制一个物体,则使用clone,该标的复印件是:

$arr = array($obj, clone $obj);
问题回答

你们需要创建新类别的例子。

$obj2 = new stdClass;
$obj2->AAA = "bbb";
$obj2->BBB = "aaa";

$arr = array($obj, $obj2);

否则,您的阵列中就有2个同标点。 最新说明改变了基本目标。





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签