Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
指定类';PHP中对象的类型_Php_Types_Oop - Fatal编程技术网

指定类';PHP中对象的类型

指定类';PHP中对象的类型,php,types,oop,Php,Types,Oop,有没有办法在PHP中指定对象的属性类型? 例如,我有一些类似于: class foo{ public bar $megacool;//this is a 'bar' object public bar2 $megasupercool;//this is a 'bar2' object } class bar{...} class bar2{...} 如果没有,您知道在PHP的未来版本中,有一天它是否会成为可能吗?否。您可以使用函数参数,但不能声明变量或类属性的类型。您正在寻找的是类型提

有没有办法在PHP中指定对象的属性类型? 例如,我有一些类似于:

class foo{
 public bar $megacool;//this is a 'bar' object
 public bar2 $megasupercool;//this is a 'bar2' object
}


class bar{...}
class bar2{...}

如果没有,您知道在PHP的未来版本中,有一天它是否会成为可能吗?

否。您可以使用函数参数,但不能声明变量或类属性的类型。

您正在寻找的是类型提示,并且部分可用,因为PHP 5/5.1在函数声明中,但不是在类定义中使用它的方式

这项工作:

<?php
class MyClass
{
   public function test(OtherClass $otherclass) {
        echo $otherclass->var;
    }
我不认为这是计划在未来,至少我不知道它是计划在PHP6

但是,您可以在对象中使用强制执行自己的类型检查规则。不过,它不会像
OtherClass$OtherClass
那么重要


您可以指定对象类型,同时通过setter方法参数中的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;
    }
}

除了前面提到的类型提示之外,您还可以记录属性,例如

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

可以帮助某些IDE提供代码帮助。

当前类中可以有其他类对象,但在使用前必须在承包商(或其他地方)中创建

class Foo {
  private Bar $f1;
  public Bar2 $f2;
  public function __construct() {
    $f1 = new Bar();
    $f2 = new Bar2();
}}

class Bar1 {...}
class Bar2 {...}

应该注意的是,类型提示对于标量类型是不可用的。@Gordon:没错。当然,您可以在方法中的一个简短if条件中检查特定类型。如果不满意,则根据给定的参数抛出异常。@faileN yes,类似或任何特定的is_*函数。这是一个不错的选择,非常适合用于文档编制。我不知道这样可以重载方法。美好的
class Foo {
  private Bar $f1;
  public Bar2 $f2;
  public function __construct() {
    $f1 = new Bar();
    $f2 = new Bar2();
}}

class Bar1 {...}
class Bar2 {...}