ImDom
ImDom

Reputation: 107

php variable that points to another variable

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 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

Upvotes: 1

Views: 890

Answers (2)

Yacoby
Yacoby

Reputation: 55465

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

Upvotes: 6

sjobe
sjobe

Reputation: 2837

$user = &$users;

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

Upvotes: 1

Related Questions