1

I have a function like this:

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

I can check if all given arguments belong to the same type/class (class, in this case) using functions like get_class(), is_*() or even ctype_*() but that operates (as far as I understand) at the single element level.

What I would ideally like to do is something similar to the in_array() function but comparing the class of all elements in the array, so I would do something like in_class($class, $arguments, true).

I could do something like this:

$check = true;

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

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

So my question is... is there a defined function for this? Or, at least, a better/more elegant method to accomplish this?

Sam
  • 7,252
  • 16
  • 46
  • 65
Julio María Meca Hansen
  • 1,303
  • 1
  • 17
  • 37

2 Answers2

1

You could use array_reduce(...) to apply the function on every element. If your goal is to write a one-liner you could use create_function(...) as well.

Example of 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.
?>
Jakob Pogulis
  • 1,150
  • 2
  • 9
  • 19
0

I think this SO question can fit to your requirement. It has used ReflectionMethod

Community
  • 1
  • 1
Smile
  • 2,770
  • 4
  • 35
  • 57