OO method inside a variable

View: New views
3 Messages — Rating Filter:   Alert me  

OO method inside a variable

by Simone Nanni :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hi everybody,
i'm trying to apply a method to an object getting its name from a  
variable, that i obtain parsing an XML file.

For example:

$object = new Class;
$method = "row()"; #I'm getting this from the XML parser
$object->$method; #I've an error here...

Obviously the method inside the class exists.
How can i do it?
Thanks a lot in advance.

Simone Nanni


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


Re: OO method inside a variable

by Eddie Drapkin :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

On Wed, Nov 4, 2009 at 4:36 PM,  <simone.nanni@...> wrote:

> Hi everybody,
> i'm trying to apply a method to an object getting its name from a variable,
> that i obtain parsing an XML file.
>
> For example:
>
> $object = new Class;
> $method = "row()"; #I'm getting this from the XML parser
> $object->$method; #I've an error here...
>
> Obviously the method inside the class exists.
> How can i do it?
> Thanks a lot in advance.
>
> Simone Nanni
>
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>

Use call_user_func() and call_user_func_array() with the callback format:

array($instance, 'method'); for instance methods or
array('class_name', 'method'); for static methods

so you'd want:

$obj = new Class();
$method = "row";
call_user_func(array($obj, $method));

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


Re: OO method inside a variable

by Robert Cummings :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

simone.nanni@... wrote:

> Hi everybody,
> i'm trying to apply a method to an object getting its name from a  
> variable, that i obtain parsing an XML file.
>
> For example:
>
> $object = new Class;
> $method = "row()"; #I'm getting this from the XML parser
> $object->$method; #I've an error here...
>
> Obviously the method inside the class exists.
> How can i do it?
> Thanks a lot in advance.

Your problem is the inclusion of parameters in the $method. You can do
the following:

<?php

     $object = new Class;
     $method = 'row';
     $ret = $object->$method();

?>

Or if you insist on embedded parameters (but this is a security risk):

<?php

     $object = new Class;
     $method = 'row()';
     $ret = eval( "return \$object->$method;" );

?>

Cheers,
Rob.
--
http://www.interjinn.com
Application and Templating Framework for PHP

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php