tags:

views:

334

answers:

6

Ok I have a string...

$a_string = "Product";

and I want to use this string in a call to a object like this:

$this->$a_string->some_function();

How the dickens do I dynamically call that object?

(don't think Im on php 5 mind)

A: 

EDIT: You need to be running PHP5 in order to do any method chaining. After that, what you have is perfectly legal.

webdestroya
But this isn't true. What you can't do in PHP4 is chaining method calls like this: `$obj->method1(10)->method2(42);` (that, and `public/private/static` properties and methods)
ZJR
You do not need to be running PHP 5.x to do any object oriented programming. There is an OO model in older versions as well.
Ian P
Ok, updated to reflect that.
webdestroya
A: 

In the code you've shown, it looks like you're trying to call a function from string itself. My guess is that you want to call a function from a class with the same name as that string, in this case "Product."

This is what that would look like:

$this->Product->some_function();

It seems you might instead be looking for something like this:

$Product = new Product();
$Product->some_function();
editor
A: 

Let's see if I got your intentions correctly...

$some_obj=$this->$a_string;
$some_obj->some_function();
ZJR
+2  A: 

So you the code you want to use would be:

$a_string = "Product";
$this->$a_string->some_function();

This code implies a few things. A class called Product with the method some_function(). $this has special meaning, and is only valid inside a class definition. So another class would have a member of Product class.

So to make your code legal, here's the code.

class Product {
    public function some_function() {
        print "I just printed Product->some_function()!";
    }
}

class AnotherClass {

    public $Product;

    function __construct() {
        $this->Product = new Product(); 
    }

    public function callSomeCode() {
        // Here's your code!
        $a_string = "Product";
        $this->$a_string->some_function();
    }
}

Then you can call it with this:

$MyInstanceOfAnotherClass = new AnotherClass();
$MyInstanceOfAnotherClass->callSomeCode();
artlung
A: 

So you've got an object, and one of it's properties (called "Product") is another object which has a method called some_function().

This works for me (in PHP5.3):

<?PHP


class Foo {
     var $bar;
}

class Bar {
      function some_func(){
           echo "hello!\n";
      }
}

$f = new Foo();
$f->bar = new Bar();

$str = 'bar';

$f->$str->some_func(); //echos "hello!"

I don't have PHP4 around, but if it doesn't work there, you might need to use call_user_func() (or call_user_func_array() if you need to pass arguments to some_function()

timdev
+1  A: 

I seem to have read this question differently from everyone else who's responded, but are you trying to use variable variables?

banzaimonkey