2016-04-27 32 views
1

我使用這個PHP庫如何調用來自用戶輸入的任何方法或屬性

fzaninotto/Faker

 <?php 
     // require the Faker autoloader 
     require_once '/path/to/Faker/src/autoload.php'; 
     // use the factory to create a Faker\Generator instance 
     $faker = Faker\Factory::create(); 
     $name=$_POST['name']; 
     switch ($name) { 
     case 'text': 
       echo $faker->text; 
      break; 
      case 'name': 
       echo $faker->name; 
      break; 
      case 'address': 
       echo $faker->address; 
      break; 

     default: 
      echo $faker->anything; 
      break; 
    } 
    ?> 

你可以看到叫「騙子」
我需要的任何方法或屬性使用switch語句。
有沒有更好的辦法做事?

<form action="index.php" method="post"> 
<input type="text" name="name" value="text" /><br><br> 
<input type="submit" value="Run" /> 
</form> 

我想要做的就是這樣的事情

<?php 
$name=$_POST['name']; 
echo $faker->$name; 
//So if user type text 
echo $faker->text ; 
//or if user type "words($nb = 3, $asText = false)" 
echo $faker->words($nb = 3, $asText = false); 
?> 
+0

你所提出的建議你可以做怎麼過的一個參數('$ faker->字()'),你需要額外的邏輯,否則使用大括號:'echo $ faker - > {$ name};'如果'$ name'等於'address',那麼您將執行等效的'echo $ faker->地址;' – Rasclatt

+0

「你需要額外的邏輯,否則使用大括號「。我如何額外登錄?請幫助,如果你有任何想法在你的腦海裏 – daulat

+0

好吧,你說什麼,用戶會鍵入類似的東西,如「詞| {」nb「:」3「,」文本「:」假「},那麼你可以搜索'''使用'strpos()',然後''爆炸(')'使用'|'將字符串解析成第二個變量爲json,第一個爲支撐值。 – Rasclatt

回答

0
<?php 
    $userinput='paragraph|{"nb":"10","text":"true"}'; 
     $explode=explode('|',$userinput); 
     $functionName=$explode[0]; 
     $arg=json_decode(end($explode),true); 
     echo call_user_func_array(array($this->faker, $functionName), $arg); 
?> 
相關問題