php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #37450 Type Hinting with Array of Objects
Submitted: 2006-05-15 21:47 UTC Modified: 2006-05-15 21:55 UTC
Votes:11
Avg. Score:4.3 ± 0.7
Reproduced:9 of 9 (100.0%)
Same Version:5 (55.6%)
Same OS:9 (100.0%)
From: mega-squall at caramail dot com Assigned:
Status: Wont fix Package: Feature/Change Request
PHP Version: 5.1.4 OS: ALL
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: mega-squall at caramail dot com
New email:
PHP Version: OS:

 

 [2006-05-15 21:47 UTC] mega-squall at caramail dot com
Description:
------------
Type Hinting is compatible with array and objects, but not with array containing ONLY instances of single chosen class (array of instances). This would be appreciated, if relevant with the structure of arrays.

Reproduce code:
---------------
class B {
  public $field;
  public __construct ($param) { $this->field = $param; }
}

class A {
  public function method (B[] $parameters){
    foreach ($parameters as $object) {
      echo $object->field . "\n";
    }
  }
}

$b = Array ();
for ($count=0; $count<10; $count++) {
  $b[] = new B ($count);
}

$a = new A ();
$a->method ($b);

Expected result:
----------------
0
1
2
3
4
5
6
7
8
9

Actual result:
--------------
Parse error: syntax error, unexpected '[', expecting '&' or T_VARIABLE in __FILE__ on line __LINE__


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2006-05-15 21:53 UTC] helly@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

That's impossible and never will be.

But you can do that more or less yourself.

Derive a class that implements ArrayAccess or reuse ArrayObject/ArrayIterator. And overload its offsetSet(). In the method body you add the check to ensure only what you want can go in.

Now if that class accepts only B's you may call it ArrayOfB and the use ArrayOfB as you typehint.

So obviously  this is a question for general@php.net
 [2006-05-15 21:55 UTC] derick@php.net
Its a valid request... so marking as "Wont fix" instead.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Jul 05 19:01:30 2024 UTC