加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

在PHP中通过引用传递

发布时间:2020-12-13 16:48:42 所属栏目:PHP教程 来源:网络整理
导读:我对 PHP中的引用工作方式有一点普遍的不满,我自己来自Java背景.这可能是之前在SO上讨论的,所以如果这看起来多余,我很抱歉. 我将给出一个代码示例来说明问题.假设我们有一个Person类: ?phpclass Person { private $name; public function __construct($name
我对 PHP中的引用工作方式有一点普遍的不满,我自己来自Java背景.这可能是之前在SO上讨论的,所以如果这看起来多余,我很抱歉.

我将给出一个代码示例来说明问题.假设我们有一个Person类:

<?php

class Person 
{
    private $name;

    public function __construct($name)
    {
        $this->name = $name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }
}

?>

以及用法:

<?php

require_once __DIR__ . '/Person.php';

function changeName(Person $person)
{
    $person->setName("Michael");
}

function changePerson(Person $person)
{
    $person = new Person("Jerry");
}

$person = new Person("John");

changeName($person);
echo $person->getName() . PHP_EOL;

changePerson($person);
echo $person->getName() . PHP_EOL;

?>

现在我和许多其他人从Java或C#编程到PHP,希望输出上面的代码:

Michael
Jerry

但是,它没有,它输出:

Michael
Michael

我知道它可以通过使用&来修复.通过查看,我明白这是因为引用按值(引用的副本)传递给函数.但这对我来说是一种意外/不一致的行为,所以问题是:他们选择这样做是否有任何特定的理由或好处?

解决方法

如果以这种方式使用,您的代码将按预期工作:

function changePerson(Person &$person) // <- & to state the reference
{
    $person = new Person("Jerry");
}

$person = new Person("John");

changeName($person);
echo $person->getName() . PHP_EOL;

changePerson($person);
echo $person->getName() . PHP_EOL;

请参阅输出:http://codepad.org/eSt4Xcpr

One of the key-points of PHP 5 OOP that is often mentioned is that “objects are passed by references by default”. This is not completely true.

A PHP reference is an alias,which allows two different variables to write to the same value. 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.

引自http://php.net/manual/en/language.oop5.references.php.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读