【问题标题】:PHP type function parameter to check要检查的 PHP 类型函数参数
【发布时间】:2017-04-12 00:03:36
【问题描述】:

如何将类型传递给函数,以便它可以检查对象是否来自传递的类型。

我的尝试似乎不起作用:

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);

【问题讨论】:

  • 只需将类型名称作为字符串传递。
  • get_class()。它不适用于继承,但可能足以满足您的需求。
  • 或者使用 php 中的 is_a($object,$classname) 函数 php.net/manual/en/function.is-a.php
  • 感谢您的快速回复,但不,我不想将其作为字符串传递。 Java / C#中没有类似泛型方法的东西吗?
  • not pass it as strint 那么呢? , 但是让我们结合is_a($object,get_class($otherwhatver)),如果你真的来自C#,那么你将很难使用php ;-)

标签: php types


【解决方案1】:

如果你想像上面那样实例化类型,你可以将类名作为字符串传递。

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');

【讨论】:

  • 所以看起来没有工作直接询问类型,只能通过字符串操作?
【解决方案2】:

我不确定我是否正确理解了您的问题,但如果我是对的,这就是我如何创建一个列表对象而不是只能存储一个特定类型或对象:

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;
}
}

【讨论】:

    【解决方案3】:
    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");
    

    http://www.php.net/manual/en/function.is-subclass-of.php

    【讨论】:

      猜你喜欢
      • 2011-11-24
      • 2021-12-09
      • 2012-02-08
      • 1970-01-01
      • 1970-01-01
      • 2020-05-13
      • 1970-01-01
      • 2020-09-21
      • 1970-01-01
      相关资源
      最近更新 更多