2010-05-02 71 views
4

好吧,我有一個字符串...PHP字符串對象名

$a_string = "Product"; 

,我想用這個字符串中調用這樣一個對象:

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

狄更斯怎麼辦我動態調用該對象?

(不要覺得我在PHP 5記)

+0

您是否嘗試過的代碼?..另外' echo phpversion();''會顯示你是否使用PHP 5. – salathe 2010-05-03 08:18:10

+0

爲什麼不使用call_user_func(或call_user_func_array)? – zfm 2012-09-05 07:51:49

回答

3

所以你想要使用的代碼是:

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

此代碼意味着一些事情。使用方法some_function()的類叫Product$this有特殊含義,並且只有裏面有一個類的定義。所以另一個班級將有Product班的成員。

因此,要使您的代碼合法,以下是代碼。

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

然後你就可以用這個稱呼它:

$MyInstanceOfAnotherClass = new AnotherClass(); 
$MyInstanceOfAnotherClass->callSomeCode(); 
0

編輯:你需要爲了做任何方法鏈接到運行PHP5。之後,你擁有的是完全合法的。

+0

但這不是事實。你不能在PHP4做的是鏈接的方法調用是這樣的:'$ obj->方法一(10) - >方法2(42);'(即和'公共/私營/ static'屬性和方法) – ZJR 2010-05-02 23:59:25

+0

你做不需要運行PHP 5.x來執行任何面向對象的編程。舊版本中也有OO模型。 – 2010-05-02 23:59:52

+0

好的,更新以反映這一點。 – 2010-05-03 00:03:03

0

在你顯示的代碼中,它看起來像你試圖從字符串本身調用一個函數。我的猜測是你想從一個與該字符串同名的類中調用一個函數,在這種情況下是「Product」。

這是一個什麼樣子:

$this->Product->some_function(); 

看來你可能反而會尋找這樣的事情:

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

讓我們來看看,如果我得到了正確的你的意圖......

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

所以,你有一個對象,它的一個特性(稱爲「產品」)是有一個方法叫some_function另一個對象()。

這個工作對我來說(在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!" 

我沒有PHP4左右,但如果它沒有在那裏工作,你可能需要使用call_user_func()(或call_user_func_array()如果你需要傳遞參數給some_function()