Forum Moderators: coopster

Message Too Old, No Replies

variable functions explained

         

AffiliateDreamer

8:28 pm on Jan 5, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I am reading the docs on php, and in the section of functions it is talkign about variable f'ns.

This doens't make sense to me:

<?php
class Foo
{
function Variable()
{
$name = 'Bar';
$this->$name(); // This calls the Bar() method
}

function Bar()
{
echo "This is Bar";
}
}

$foo = new Foo();
$funcname = "Variable";
$foo->$funcname(); // This calls $foo->Variable()

?>

How is $funcname(); called as a method of $foo when the class defintion doesn't contain $funcname() as a function/method?

coopster

8:50 pm on Jan 5, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



But the class does indeed have a function/method named "Variable":
function Variable() 
{
$name = 'Bar';
$this->$name(); // This calls the Bar() method
}

So PHP will render the variable first, thereby making it a variable function and calling ...

$foo->$funcname();

... is parsed to the variable value and the function is requested as ...
$foo->Variable();

AffiliateDreamer

11:10 pm on Jan 5, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hmm, that just doesn't sit well with me!

Using the -> to me means that you are either assigning a variable that is defined IN the class, or you are calling a function/method of the class.

How $foo->$funcname() works is beyond me, but I do understand what is happening behind the scenese.

Ok as I right this post it is becoming clearer, basically $funname() gets replaced by Variable since that is what was assigned to the 'variable'.

Still kinda 'hacky' to me hehe.