gpt4 book ai didi

php - 为什么我的变量会发生这种情况?

转载 作者:行者123 更新时间:2023-12-04 05:49:40 26 4
gpt4 key购买 nike

<?php

// $searchResult is type of Outcome
// This is what we do:
dList::lessAnchor($searchResult)->showElement();
dList::moreAnchor($searchResult)->showElement();

/**
* @returns vAnchor (can get showed with showElement() - not part of the problem)
*/
public static function lessAnchor(Outcome $searchResult){
$searchData = $searchResult->searchData;
$searchData->Page = $searchData->Page - 1; // (!1)
return self::basicAnchor($searchData, "Back");
}

/**
* @returns vAnchor (can get showed with showElement() - not part of the problem)
*/
public static function moreAnchor(Outcome $searchResult){
$searchData=$searchResult->searchData;
$searchData->Page = $searchData->Page + 1; // (!2)
return self::basicAnchor($searchData, "More");
}

当我打电话时 dList::lessAnchor()$searchResult ,它修改了 $searchData->Page 的属性如您所见,将其减 1,标记为 (!1) .
过了一会儿(下面一行),我调用 dList::moreAnchor()$searchResult再次。

为什么我看到 Page属性在 (!2) 处减少 1标记?我没有通过 $searchResult引用。

最佳答案

看看the documentation : 这是预期的行为。

As of PHP 5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.



如果你想避免这种情况,你应该 clone your object有需要的地方。就像这样:
public static function lessAnchor(Outcome $searchResult){
$searchData = clone $newResult->searchData; //$searchData now is a new object
$searchData->Page=$searchData->Page-1; // (!1)
return self::basicAnchor($searchData,"Back");
}

关于php - 为什么我的变量会发生这种情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10235312/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com