通过const引用传递对象? [英] Passing an object by const reference?

查看:130
本文介绍了通过const引用传递对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,当您希望函数能够从对象读取而不希望对其进行修改时,可以将 const 引用传递给该函数。

In C++ when you want a function to be able to read from an object, but not modify it, you pass a const reference to the function. What is the equivalent way of doing this in php?

我知道php5中的对象默认是通过引用传递的,但是出于可读性考虑,我认为我将继续使用&符在变量名之前,像这样:

I know objects in php5 are passed by reference by default, but for readability I think I will continue to use the ampersand before the variable name, like this:

function foo(&$obj)
{

}


推荐答案

如果要传递对象

<?php
function changeObject($obj) {
  $obj->name = 'Mike';
}

$obj = new StdClass;
$obj->name = 'John';

changeObject(clone $obj);
echo $obj->name; // John

changeObject($obj);
echo $obj->name; // Mike




我知道php5中的对象默认是通过引用传递的,但出于可读性考虑,我想我会继续在变量名之前使用&符号

I know objects in php5 are passed by reference by default, but for readability I think I will continue to use the ampersand before the variable name

这是您的电话,但我发现这样做只会它读起来更像C ++。或者,您可以通过在函数定义中使用类型提示来显示正在传递对象:

That's your call but I find that would simply make it read more like C++. Alternativly, you can show that an object is being passed in by using type-hinting in your function definition:

function foo(StdClass $obj)
{

}

很明显, $ obj 是一个对象,可以假定它已通过引用传递。

Once it's clear that $obj is an object it can be assumed that it's being passed by reference.

这篇关于通过const引用传递对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆