Iterable objects and array type hinting?
I think you mean instanceof Iterator
, PHP doesn't have an Iterable
interface. It does have a Traversable
interface though. Iterator
and IteratorAggregate
both extend Traversable
(and AFAIK they are the only ones to do so).
But no, objects implementing Traversable
won't pass the is_array()
check, nor there is a built-in is_iterable()
function. A check you could use is
function is_iterable($var) {
return (is_array($var) || $var instanceof Traversable);
}
To be clear, all php objects can be iterated with foreach, but only some of them implement Traversable
. The presented is_iterable
function will therefore not detect all things that foreach can handle.
Type hinting in PHP 7 - array of objects
It's not included.
If it's not included, do you have Any clue why it was not included when type hinting was added?
With the current array implementation, it would require checking all array elements at runtime, because the array itself contains no type information.
It has actually already been proposed for PHP 5.6 but rejected: RFC "arrayof" - interestingly not because of performance issues which turned out to be neglible, but because there was no agreement in how exactly it should be implemented. There was also the objection that it is incomplete without scalar type hints. If you are interested in the whole discussion, read it in the mailing list archive.
IMHO array type hints would provide most benefit together with typed arrays, and I'd love to see them implemented.
So maybe it's about time for a new RFC and to reopen this discussion.
Partial Workaround:
you can type hint variadic arguments and thus write the signature as
function findUserByAge(int $age, User ...$users) : array
Usage:
findUserByAge(15, ...$userInput);
In this call, the argument $userInput
will be "unpacked" into single variables, and in the method itself "packed" back into an array $users
. Each item is validated to be of type User
. $userInput
can also be an iterator, it will be converted to an array.
Unfortunately there is no similar workaround for return types, and you can only use it for the last argument.
type hinting an array
Most of the standard library is not type annotated. mypy
is using the stubs for the standard library from the typeshed project (which along with the standard library, also contains annotations for popular third-party library as provided by various contributers). For the array
module, you can see that it is type annotated as generic:
import sys
from typing import Any, BinaryIO, Generic, Iterable, MutableSequence, Tuple, TypeVar, Union, overload
from typing_extensions import Literal
_IntTypeCode = Literal["b", "B", "h", "H", "i", "I", "l", "L", "q", "Q"]
_FloatTypeCode = Literal["f", "d"]
_UnicodeTypeCode = Literal["u"]
_TypeCode = Union[_IntTypeCode, _FloatTypeCode, _UnicodeTypeCode]
_T = TypeVar("_T", int, float, str)
typecodes: str
class array(MutableSequence[_T], Generic[_T]):
typecode: _TypeCode
itemsize: int
@overload
def __init__(self: array[int], typecode: _IntTypeCode, __initializer: bytes | Iterable[_T] = ...) -> None: ...
@overload
def __init__(self: array[float], typecode: _FloatTypeCode, __initializer: bytes | Iterable[_T] = ...) -> None: ...
@overload
def __init__(self: array[str], typecode: _UnicodeTypeCode, __initializer: bytes | Iterable[_T] = ...) -> None: ...
@overload
def __init__(self, typecode: str, __initializer: bytes | Iterable[_T] = ...) -> None: ...
def append(self, __v: _T) -> None: ...
...
The solution is to use MutableSequence
as noted as answered in the question you linked to. Note, since Python 3.9+, typing.MutableSequence
(along with things like typing.List
and typing.Dict
) have been deprecated, and the types themselves support generics, so use import collections
and collections.abc.MutableSequence
PHPDoc type hinting for array of objects?
Use:
/* @var $objs Test[] */
foreach ($objs as $obj) {
// Typehinting will occur after typing $obj->
}
when typehinting inline variables, and
class A {
/** @var Test[] */
private $items;
}
for class properties.
Previous answer from '09 when PHPDoc (and IDEs like Zend Studio and Netbeans) didn't have that option:
The best you can do is say,
foreach ($Objs as $Obj)
{
/* @var $Obj Test */
// You should be able to get hinting after the preceding line if you type $Obj->
}
I do that a lot in Zend Studio. Don't know about other editors, but it ought to work.
PHP Type hinting to allow Array or ArrayAccess
No, there is no "clean" way of doing it.
The array
type is a primitive type. Objects that implement the ArrayAccess
interface are based on classes, also known as a composite type. There is no type-hint that encompasses both.
Since you are using the ArrayAccess
as an array you could just cast it. For example:
$config = new Config;
$lol = new I_Use_A_Config( (array) $config);
If that is not an option (you want to use the Config
object as it is) then just remove the type-hint and check that it is either an array or an ArrayAccess
. I know you wanted to avoid that but it is not a big deal. It is just a few lines and, when all is said and done, inconsequential.
PHP Traversable type hint
PHP 7.1 introduces the iterable
type declaration for this purpose, which accepts both arrays and instances of \Traversable
.
In previous versions, you'll have to omit the type declaration.
Function return type hinting for an array of objects in PHP7
I actually understand what you mean, but the answer unfortunately is that you can't do that. PHP7 lacks that kind of expressivity, so you can either declare your function to return "array" (a generic array) or you have to create a new class ItemArray which is an array of Item (but that meaning you will have to code it yourself).
There is currently no way to express "I want an array of Item" instances.
EDIT: As an added reference, here the "array of" RFC of what you wanted to do, it has been declined due to various reasons.
Related Topics
Change Single Variable Value in Querystring
How to Check If a Directory Exists? "Is_Dir", "File_Exists" or Both
Check If Url Has Certain String with PHP
Display Output in Parts in PHP
Using Regex to Filter Attributes in Xpath with PHP
How to Avoid Code Repetition with PHP SQL Prepared Statements
PHP Object Attribute with Dot in Name
Why PHP Iteration by Reference Returns a Duplicate Last Record
PHP Regex Word Boundary Matching in Utf-8
How to Dynamically Build Queries with Pdo
Using PHP as a Template Engine
Display Custom Order Meta Data Value in Email Notifications Woocommerce
Proper Repository Pattern Design in PHP
How to Rotate Image and Save the Image
Session Unset, or Session_Destroy
Extract a Substring Between Two Characters in a String PHP
Fatal Error: Call to Undefined Function SQLsrv_Connect() in C:\Xampp\Htdocs