Jump to content

Weird issue with reference argument across classes


TheKog

Recommended Posts

This issue cropped up in a CakePHP app but I think our problem is more related to something we don;t understand about PHP. Any advice is much appreciated!

 

In a Bait controller class a function foo from the Bait model class is invoked:

function test()

{

Bait::foo($xxx); // works correctly

$this->Bait->foo($xxx); // does not work

}

 

In Bait model function foo() takes the parm by ref and sets it's

value:

 

function foo(&$msg)

{

$msg = "HOWDY DOODY";

}

 

ERROR is Notice (8): Undefined variable:  xxx [CORE/app/controllers/baits_controller.php, line 71]

 

If I put function foo within the Bait controller class $this->foo()

works fine. However when I put it in the model using the $this->Bait->foo() invocation syntax seems to ignore the parameter by reference.

Calling the Bait::foo() method like that, is as if your calling a static function.

 

When you use the $this-> method, your calling it from within an instance of the Bait class, so you don't need to include the class name ($this->Bait->foo() bold part.)

Sorry if I wasn't specific enough. In the contoller it's class BaitsController -- it is invoking a funnction that is in another class called BaitModel which is associated with the BaitsController class. It just seems using $this causes the interpreter to ignore the function definition's parameters by argument. $this is instantiated and does indeed call the correct function -- it just does not handle the parameter by reference correctly.

I can't seem to replicate it.

Maybe I don't understand the problem.

 

Is this basically what you mean:

<?php
class a{
var $foobar;
function a(){
	$this->bar($this->foobar);
	$this->bar($a);
}
function bar(&$bar){
	$bar = "It worked!";
}	
}

$a = new a();
echo "A testing:\n";
echo $a->foobar;


class b{
var $a;
var $foobar;
function bar(){
	$this->a->bar($this->foobar);
}
function foobar(&$test){
	a::bar($test);
}
}

echo "\n\nB testing:\n";
$b = new b($foobar);
$b->a = $a;
$b->bar();
echo $b->foobar;



echo "\n\nMore testing:\n";
$foobar = "This should go away.";
$b->foobar($foobar);
echo $foobar;
?>

?

 

The code above produces:

 

A testing:

It worked!

 

B testing:

It worked!

 

More testing:

It worked!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.