有没有办法在PHP中指定对象的属性类型? 例如,我有类似的东西:
class foo{
public bar $megacool;//this is a 'bar' object
public bar2 $megasupercool;//this is a 'bar2' object
}
class bar{...}
class bar2{...}
如果没有,你知道在一天的PHP未来版本中是否有可能吗?
答案 0 :(得分:11)
除了已经提到的TypeHinting之外,您还可以记录该属性,例如
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
@var annotation
可以帮助某些IDE提供代码帮助。
答案 1 :(得分:6)
您正在寻找的是名为Type Hinting,并且在PHP 5 / 5.1中部分可用于函数声明,但不是您希望在类定义中使用它的方式。
这有效:
<?php
class MyClass
{
public function test(OtherClass $otherclass) {
echo $otherclass->var;
}
但这不是:
class MyClass
{
public OtherClass $otherclass;
我不认为这是未来的计划,至少我不知道它是否计划用于PHP 6.
但是,您可以在对象中使用getter and setter functions强制执行自己的类型检查规则。不过,它不会像OtherClass $otherclass
那样具有强大的意义。
答案 2 :(得分:2)
没有。您可以使用type hinting作为函数参数,但不能声明变量或类属性的类型。
答案 3 :(得分:1)
您可以在当前类中包含其他类对象,但在使用前必须在__contractor(或其他位置)中创建它。
document.querySelectorAll()
答案 4 :(得分:0)
您可以指定对象类型,同时通过setter-method参数中的type-hint将对象注入var。像这样:
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;
}
}