【问题标题】:Check if all parameters for a given function belong to the same class检查给定函数的所有参数是否属于同一类
【发布时间】:2013-05-01 10:28:02
【问题描述】:

我有这样的功能:

// merge - merge two or more given trees and returns the resulting tree
function merge() {
    if ($arguments = func_get_args()) {
        $count = func_num_args();

        // and here goes the tricky part... :P
    }
}

我可以使用get_class()is_*() 甚至ctype_*() 之类的函数检查所有给定参数是否属于同一类型/类(在本例中为类),但它的操作(据我所知)在单个元素级别。

理想情况下,我想做的是类似于in_array() 函数但比较数组中所有元素的类,所以我会做类似in_class($class, $arguments, true) 的事情。

我可以这样做:

$check = true;

foreach ($arguments as $argument) {
    $check &= (get_class($argument) === "Helpers\\Structures\\Tree\\Root" ? true : false);
}

if ($check) {
    // continue with the function execution
}

所以我的问题是……有为此定义的函数吗?或者,至少,有更好/更优雅的方法来实现这一点?

【问题讨论】:

  • get_object_vars 或 get_class_vars 可能吗? php.net/manual/en/function.get-object-vars.php
  • 你到底想做什么?
  • 不,我需要获取每个参数的类名并对其进行检查。这两种方法将公开每个参数属性(在我的情况下为$attributes),但它不起作用:P
  • @NullVoid 我想检查是否所有给定的参数都是Tree 类的实例(这是一个合并树的函数)。

标签: php class arguments elements


【解决方案1】:

您可以使用array_reduce(...) 将函数应用于每个元素。如果你的目标是写一个单行,你也可以使用create_function(...)

array_reduce 示例

<?php
    class foo { }
    class bar { }

    $dataA = array(new foo(), new foo(), new foo());
    $dataB = array(new foo(), new foo(), new bar());

    $resA = array_reduce($dataA, create_function('$a,$b', 'return $a && (get_class($b) === "foo");'), true);
    $resB = array_reduce($dataB, create_function('$a,$b', 'return $a && (get_class($b) === "foo");'), true);

    print($resA ? 'true' : 'false'); // true
    print($resB ? 'true' : 'false'); // false, due to the third element bar.
?>

【讨论】:

  • 工作就像一个魅力。非常感谢! :)
【解决方案2】:

我认为这个 SO question 可以满足您的要求。它使用了ReflectionMethod

【讨论】:

    猜你喜欢
    • 2012-10-26
    • 1970-01-01
    • 1970-01-01
    • 2015-02-19
    • 1970-01-01
    • 2011-08-10
    • 2021-11-13
    • 1970-01-01
    • 2023-04-09
    相关资源
    最近更新 更多