开发者

PHP string to object name

开发者 https://www.devze.com 2022-12-28 17:44 出处:网络
Ok I have a string... $a_string = \"Product\"; and I want to u开发者_运维百科se this string in a call to a object like this:

Ok I have a string...

$a_string = "Product";

and I want to u开发者_运维百科se 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)


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();


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


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();


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


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

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


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()

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号