2013-05-07 44 views
1

我有这样的功能:检查给定函数的所有参数都属于同一类

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

所以我的问题是...是有一个定义的功能呢?或者,至少,一个更好/更优雅的方法来实现这一目标?

+0

get_object_vars或get_class_vars也许? http://php.net/manual/en/function.get-object-vars.php – 2013-05-07 12:55:36

+0

你到底想做什么? – NullPointer 2013-05-07 12:58:42

+0

不,我需要为每个参数获取类名并对它进行检查。这两个方法将暴露每个参数属性(在我的情况下''属性'),但它不会工作:P – 2013-05-07 13:01:44

回答

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. 
?> 
+0

工作就像一个魅力。非常感谢! :) – 2013-05-07 13:37:35

相关问题