Is there a way to specify an object's attribute's type in PHP ? for example, I'd 开发者_如何学Chave something like :
class foo{
public bar $megacool;//this is a 'bar' object
public bar2 $megasupercool;//this is a 'bar2' object
}
class bar{...}
class bar2{...}
If not, do you know if it will be possible in one of PHP's future version, one day ?
In addition to the TypeHinting already mentioned, you can document the property, e.g.
class FileFinder
{
/**
* The Query to run against the FileSystem
* @var \FileFinder\FileQuery;
*/
protected $_query;
/**
* Contains the result of the FileQuery
* @var Array
*/
protected $_result;
// ... more code
The @var annotation
would help some IDEs in providing Code Assistance.
What you are looking for is called Type Hinting and is partly available since PHP 5 / 5.1 in function declarations, but not the way you want to use it in a class definition.
This works:
<?php
class MyClass
{
public function test(OtherClass $otherclass) {
echo $otherclass->var;
}
but this doesn't:
class MyClass
{
public OtherClass $otherclass;
I don't think this is planned for the future, at least I'm not aware of it being planned for PHP 6.
you could, however, enforce your own type checking rules using getter and setter functions in your object. It's not going to be as elegeant as OtherClass $otherclass
, though.
PHP Manual on Type Hinting
No. You can use type hinting for function parameters, but you can not declare the type of a variable or class attribute.
You can have other class objects in your current class, but you must make it in __contractor (or somewhere else) before use.
class Foo {
private Bar $f1;
public Bar2 $f2;
public function __construct() {
$f1 = new Bar();
$f2 = new Bar2();
}}
class Bar1 {...}
class Bar2 {...}
You can specify the object-type, while injecting the object into the var via type-hint in the parameter of a setter-method. Like this:
class foo
{
public bar $megacol;
public bar2 $megasupercol;
function setMegacol(bar $megacol) // Here you make sure, that this must be an object of type "bar"
{
$this->megacol = $megacol;
}
function setMegacol(bar2 $megasupercol) // Here you make sure, that this must be an object of type "bar2"
{
$this->megasupercol = $megasupercol;
}
}
精彩评论