我有一個類,其中一個方法接受應該是特定選項範圍之一的參數。我已經將這些選項定義爲類中的常量。如何防止用不是這些常量之一的值調用方法?如何檢查方法調用是否使用有效的類常量
有些代碼可能會更清楚我想要實現:
<?php
class Foo
{
const OPTION_A = 'a valid constant';
const OPTION_B = 'another valid constant';
public function go($option)
{
echo 'You chose: ' . $option;
}
}
$myFoo = new Foo();
$myFoo->go(Foo::OPTION_A); // ok
$myFoo->go(Foo::OPTION_B); // ok
$myFoo->go('An invalid value'); // bad - string, not one of the class constants
$myFoo->go(Bar::OPTION_A); // bad - constant is not local to this class
您可以使用反射和ReflectionClass :: getConstants方法做到這一點。看看文檔http://php.net/manual/en/reflectionclass.getconstants.php – Andreas