それがあなたの言いたいことなら、それは非常に簡単です。
function calculator() {
echo 'foo';
}
$userSelection = "calculator";
if (function_exists($userSelection)) {
$userSelection();
}
または、あなたの例のようなクラス内:
class widget {
public function __construct($userSelection) {
echo 'constructed widget<br>';
if (function_exists($userSelection)) {
$this->$userSelection();
}
}
public function calculator() {
echo 'bar';
}
}
$userSelection = "calculator";
$widget = new widget($userSelection);
または、関数がクラスの一部である場合は、クラスの外から。
class widget {
public function calculator() {
echo 'bar';
}
}
$widget = new widget();
$userSelection = "calculator";
$widget->$userSelection();
if/else ステートメントを使用して、有効な関数のみが実行されることを確認するために呼び出される関数を決定します (ユーザーの選択をサニタイズしますか、それとも単に a から取得します$_POST
か?後者は非常に悪い考えです) )。