$a...">

PHP string for object name

Ok, I have a line ...

$a_string = "Product"; 

and I want to use this line when calling such an object:

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

How do I dynamically call this object?

(I don't think Im on php 5 mind)

+4
source share
6 answers

So, the code you want to use will be as follows:

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

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

So for your code to be legal, here is 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 your code! $a_string = "Product"; $this->$a_string->some_function(); } } 

Then you can call it like this:

 $MyInstanceOfAnotherClass = new AnotherClass(); $MyInstanceOfAnotherClass->callSomeCode(); 
+3
source

It seems I read this question differently than everyone else who answered, but are you trying to use variable variables ?

+1
source

EDIT . To execute any chain of methods you need to run PHP5. After that, it’s completely legal for you.

0
source

In the code you provided, it looks like you are trying to call a function from the string itself. I assume that you want to call a function from a class with the same name as this line, in this case "Product."

Here's what it looks like:

 $this->Product->some_function(); 

It seems you could be looking for something like this:

 $Product = new Product(); $Product->some_function(); 
0
source

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

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

So, you have an object, and one of its properties (called "Product") is another object that has some_function () method.

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, but if it doesn't work there, you may need call_user_func () (or call_user_func_array () if you need to pass some_function () arguments

0
source

Source: https://habr.com/ru/post/1308627/


All Articles