如何将类型传递给函数,以便检查对象是否来自传递的类型。
我的尝试似乎无法奏效:
class Test {
function __construct() {
}
}
function check(Type) {
$x = new Test();
if ($x instanceof Type) {
print_r("the object is from the type of the passed variable! :)");
}
}
check(Test);
答案 0 :(得分:0)
如果要像上面那样实例化类型,可以将类名作为字符串传递。
function check($class_str)
{
$x = new $class_str();
if($x instanceof Test) {
print_r("the object is from the type of the passed variable! :)");
}
}
check('Test');
答案 1 :(得分:0)
我不确定我是否正确地理解了您的问题,但如果我说得对,我就是这样做的列表对象,而不是只存储一个特定的类型或对象:
class DList extends DVector {
/**
* @param string $template The name of the type to store
*/
public function __construct($template){
parent::__construct();
if(!class_exists($template)){
if(in_array($template, array(self::Bool, self::Integer, self::String, self::Float, self::Map))){
$this->_template = $template;
$this->_callback = '_isTemplateType';
} else {
throw new DListTemplateTypeException('Unable to find the class "' . $template. '" ');
}
} else {
$this->_template = $template;
$this->_callback = '_isTemplateInstance';
}
}
private function _isTemplateType($value){
return gettype($value) == $this->_template;
}
private function _isTemplateInstance($value){
return $value instanceof $this->_template;
}
}
答案 2 :(得分:0)
function check($type) {
$x = new Test();
if (is_subclass_of($x, $type)) {
print_r("the object is from the type of the passed variable! :)");
}
}
check("Test");