开发者

php variable that points to another variable

开发者 https://www.devze.com 2022-12-27 04:25 出处:网络
Was wondering if it\'s possible to have a variable point to another variable in PHP? What I\'m trying to do is to have a class instance like:

Was wondering if it's possible to have a variable point to another variable in PHP? What I'm trying to do is to have a class instance like:

$users = new User_Model();

and then have

$user

simply point to

$users

instead 开发者_C百科of making a new class instance. Is this possible? Think I saw something about it in the php manual, but cant find it again.

Would

$users = new User_Model();
$user = $users;

simply do it?

Thanks


By default in PHP 5 objects are copied by reference. So when you do

$users = new User_Model();
$user = $users;

Both $user and $users point to the same object.

However primitive types are still passed by value

$va = 1;
$vb = $va;
$va = 2;
echo $vb; //1

So you need to take the reference of the primitive value;

$va = 1;
$vb = &$va;
$va = 2;
echo $vb; //2


$user = &$users;

http://php.net/manual/en/language.references.php

0

精彩评论

暂无评论...
验证码 换一张
取 消