PHP常量引用 我是一个中级C++程序员,知道可以通过一个常数引用作为参数,以防止对实际变量的编辑。我想知道我是否可以在PHP中这样做?

PHP常量引用 我是一个中级C++程序员,知道可以通过一个常数引用作为参数,以防止对实际变量的编辑。我想知道我是否可以在PHP中这样做?,php,constants,Php,Constants,不,在PHP中没有与C++的const限定符等价的东西 这就是你所说的: <?php $a = 10; function foo($p_a) { // passing by value is the default $p_a++; } foo($a); echo $a; // prints 10 $a = 10; function bar(&$p_a) { //-------^

不,在PHP中没有与C++的
const
限定符等价的东西

这就是你所说的:

<?php
    $a = 10;
    function foo($p_a) {
        // passing by value is the default
        $p_a++;
    }
    foo($a);
    echo $a; // prints 10

    $a = 10;
    function bar(&$p_a) {
        //-------^ passing by reference
        $p_a++;
    }
    bar($a);
    echo $a; // prints 11
?>

@Salman A,它仅适用于标量,对象通过引用传递与否时的行为不同。看起来这两种方法之间没有真正的区别

<?php

class X
{
    static $instances = 0;

    public $instance;
    public $str;

    function __construct($str)
    {
        $this->instance = ++self::$instances;
        $this->str = $str;
    }

    public function __toString()
    {
        return "instance: ".$this->instance." str: ".$this->str;
    }
}

class Y extends X
{
    public function __toString()
    {
        return "Y:".parent::__toString();
    }
}

// Pass NORMAL
function modify_1($o)
{
    $o->str = __FUNCTION__;
}

// Pass BY-REFERENCE
function modify_2(&$o)
{
    $o->str = __FUNCTION__;
}

// Pass NORMAL - Obj Replace
function modify_3($o)
{
    $o = new Y(__FUNCTION__);
}

// Pass BY-REFERENCE - Obj Replace
function modify_4(&$o)
{
    $o = new Y(__FUNCTION__);
}

$x = new X('main');
echo "$x\n";

modify_1($x);
echo "$x\n";

modify_2($x);
echo "$x\n";

modify_3($x);
echo "$x\n";

modify_4($x);
echo "$x\n";
我期待着

instance: 1 str: main
instance: 1 str: main
instance: 1 str: modify_2
instance: 1 str: modify_2
Y:instance: 3 str: modify_4

所以我的结论是,;如果我们处理的是对象(本身)或标量,它似乎确实有效;但不是对象的属性或方法。

如果他来自c++(不能将对象设置为常量),他不会尝试这样做。默认情况下,从技术上讲,对象不是通过引用传递的。对象的位置/句柄通过值传递。因此,是的,您可以通过调用对象的方法来修改对象,但是在默认情况下,您实际上无法更改调用范围指向的对象。尽管如此,PHP并没有一个与C++的
const
等价的限定符。在4年多之后,以及在PHP7的功能冻结(包括标量类型提示)之后,C++的
const
限定符的等价物似乎不会很快被添加。您的标题令人困惑,因为PHP有类常量。标题看起来不错,然而,由于我没有找到任何等价物,这个答案建议克隆对象,然后将其传递给函数-,但克隆只生成一个浅拷贝。。。请看下面我的答案;你的案例确实适用于标量;我添加我的答案只是为了完整性,为了所有最终在这里搜索相同主题的人。
instance: 1 str: main
instance: 1 str: main
instance: 1 str: modify_2
instance: 1 str: modify_2
Y:instance: 3 str: modify_4