I've seen this code...
Code: Select all
require_once 'test.class.php';
$test =& new test();
$test->a = $b;And in functions...
Code: Select all
function foo(&$bar)
{
//
}Moderator: General Moderators
Code: Select all
require_once 'test.class.php';
$test =& new test();
$test->a = $b;Code: Select all
function foo(&$bar)
{
//
}Code: Select all
require_once 'class.test.php';
$test = new test();
//set property a
$test->a = $b;
//this will provide a clean copy of test() object without $test->a set??
$test2 =& new test();Code: Select all
$test = new test();
$test->a = 'wee';
$test2 =& $test;
$test2->b = '??';
$test3 = $test;
$test3->b = 'burger';
var_dump($test, $test2, $test3);The short answer is that in PHP4 you need to user =& when you create a new instance of an object and use &$param when you pass an object to a function in order to get objects to behave as you would expect.scottayy wrote:Why wouldn't a regular = work?
Code: Select all
$object = new MyClass();
// is the same in PHP4 as:
$foo = $bar;Code: Select all
$object =& new MyClass();That's one thing about PHP and C++. They use the same terms, but PHP's versions of them (Exceptions, function overloading, etc.) are different. Yet, since so many of us are familiar with other high-level programming languages, we assume it's the same until we take the time to read those few short chapters at the start of the manual.VladSun wrote:it made me read this manual and I found that my understanding of "PHP reference" was very mistaken (i.e. reference in PHP is not like reference in C++).
For objects, there is no point because you've already got it in PHP5. However, for arrays and anything scalar, references give you access to the actual data. There will be times when you need to alter the actual data in a separate function.scottayy wrote:Again, I don't see the point..
Actually you are saving memory because by passing by reference you are only using the memory for a reference as opposed to creating a whole copy of the object passed -- which is what you do in PHP4 if you do not use a reference. And because you are making a copy when you pass a normal parameter, the changes you make to an object will not be reflected outside the function.scottayy wrote:So when passing a reference as a function parameter, you're not really saving any memory by creating the reference, you're just creating an extra pointer to it. Again, I don't see the point.. (unless this was a php4 thing as well).