Asked  1 Year ago    Answers:  5   Viewed   16 times

I have a function that takes a member of a particular class:

public function addPage(My_Page $page)
{
  // ...
}

I'd like to make another function that takes an array of My_Page objects:

public function addPages($pages)
{
  // ...
}

I need to ensure that each element of $pages array is an instance of My_Page. I could do that with foreach($pages as $page) and check for instance of, but can I somehow specify in the function definition that the array has to be an array of My_Page objects? Improvising, something like:

public function addPages(array(My_Page)) // I realize this is improper PHP...

Thanks!

 Answers

3

No, it's not possible to do directly. You might try this "clever" trick instead:

public function addPages(array $pages)
{
    foreach($pages as $page) addPage($page);
}

public function addPage(My_Page $page)
{
    //
}

But I 'm not sure if it's worth all the trouble. It would be a good approach if addPage is useful on its own.

Thursday, April 1, 2021
 
Pradip
 
2

what you mean its call : Passing by Reference

its very simple like

function changearray(&$arr){
     $arr['x'] = 'y';
}

you can call this like :

changearray($_SESSION);
Thursday, April 1, 2021
 
Stefan
 
2

You can use the instanceof operator, to check if an object is an instance of :

  • A class
  • Or a child class of that class
  • Or an instance of a class that implements an interface

Which means that it cannot be used to detect if your object is an instance of a specific class -- as it will say "yes" if your object is an instance of a child-class of that class.


For instance, this portion of code :

class ClassA {}
class ClassB extends ClassA {}

$a = new ClassB();
if ($a instanceof ClassA) {
    echo '$a is an instanceof ClassA<br />';
}
if ($a instanceof ClassB) {
    echo '$a is an instanceof ClassB<br />';
}

Will get you this output :

$a is an instanceof ClassA
$a is an instanceof ClassB

$a, in a way, is an instance of ClassA, as ClassB is a child-class of ClassA.

And, of course, $a is also an instance of ClassB -- see the line where it's instanciated.

Thursday, April 1, 2021
 
Easen
 
1

You can call any function like that using call_user_func_array:

call_user_func_array('addArray', $a);
Thursday, April 1, 2021
 
4

A solution to get all instances of a class is to keep records of instantiated classes when you create them:

class Foo
{
  static $instances=array();
  public function __construct() {
    Foo::$instances[] = $this;
  }
}

Now the globally accessible array Foo::$instances will contain all instances of that class. Your question was a bit broad so I can not exactly say if this is what you're looking for. If not, it hopefully helps to make it more clear what you're looking for.

Saturday, May 29, 2021
 
EastSw
 
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :