2015-12-02 106 views
1

我試圖加載一個命名空間和一個名字我只知道一個變量的值的類。動態加載命名空間和類

我想這一點:

<php 
/** 
* Namespaces and class have the same name. 
*/ 

require_once($arg1 . '.class.php'); 

use \$arg1\$arg1; 

/** 
* also I have try 
* use \{$arg1}\{$arg1}; 
*/ 
$object = new $arg1(); 
var_dump($object); 
?> 

它給我回:

PHP Parse error: syntax error, unexpected '$arg1' (T_VARIABLE), expecting identifier (T_STRING) in /home/vagrant/execute.php on line 5

有任何的方式來加載這個,還是我嘗試用工廠模式,使之?

回答

0

據我所知,(不知道PHP7)鏈接變量或常量命名空間中調用是不可能的。

的情況下,

你只希望在一個可變負載取決於不斷變化的值的類(在$ argv的未來或$ _GET或者別的什麼)我經常這樣做: (這是一個控制檯腳本)

<?php 
class foo { 
    function foo() { 
     print "Hello! i'm foo class \n"; 
    } 
} 

class quux { 
    function quux() { 
     print "Hello! i'm quux class \n"; 
    } 
    function another_method() { 
     print "Bye! i'm another method \n"; 
    } 
} 


$var = $argv[1]; 
$obj = new $var; 
if ("quux" == $var){ 
    $obj->another_method(); 
} 

這是輸出我得到:)

∙ php oskar.php foo          9:58 [email protected] 
Hello! i'm foo class 
~ 
∙ php oskar.php quux          9:59 [email protected] 
Hello! i'm quux class 
Bye! i'm another method 

其實,你可以直接做new $argv[1]但你不能做new $argv[1]->another_method();的xD

0

的PHP版本正在運行&你嘗試過這樣的:

require_once $arg1 . ".class.php"; 
+0

我的PHP版本PHP 5.6.14-0 + deb8u1,而且我還有chante require_once $ arg1。 「.class.php」;但是有同樣的錯誤。 –