PHP isim alanları ile değişkenli fonksiyonlar

4 Cevap php

İsim alanları ile değişken işlevleri çağırmak için bir yol olup olmadığını merak ediyorum. Onlar html hale böylece temelde `etiketleri ayrıştırmak ve şablon fonksiyonlar göndermek için çalışıyorum

İşte bir örnek: (PHP 5.3 kullanıyorum)

 // Main php file
require_once 'template.php';
foreach (array("javascript","script","css") as $tag) {
    echo template\$tag();
}

 // template.php
 namespace template;

 function javascript() { return "Hello from javascript"; }
 function css() { return "Hello from css"; }
 function script() { return "Hello from script"; }

I keep getting Parse error: syntax error, unexpected T_VARIABLE, expecting T_STRING in ... on line 76

Teşekkürler! Mat

4 Cevap

Bu, aynı zamanda, call_user_func, sadece Variable functions Docs özelliği, kullanım için herhangi bir ihtiyaç çalışır:

require_once 'template.php';

$ns = 'template';
foreach (array('javascript', 'script', 'css') as $tag) {
    $ns_func = $ns . '\\' . $tag;
    echo $ns_func();
}

ile deneyin

 // Main php file
require_once 'template.php';
foreach (array("javascript","script","css") as $tag) {
    call_user_func("template\\$tag"); // As of PHP 5.3.0
}

 // template.php
 namespace template;

 function javascript() { return "Hello from javascript"; }
 function css() { return "Hello from css"; }
 function script() { return "Hello from script"; }

Eğer biraz bilgi here

Bu deneyin

$p = 'login';
namespace App\login; 
$test2 = '\App\\'.$p.'\\MyClass';

$test = new $test2;