【问题标题】:Can you specify the datatyp of the arguments given to a Function (PHP5)你能指定给函数的参数的数据类型吗(PHP5)
【发布时间】:2012-11-05 14:53:45
【问题描述】:

我想指定可以赋予函数的数据类型。

在此演示代码(作为示例)中,我想指定给"__construct()" 函数的参数的数据类型,以便它只需要INT 用于$idObjects 的类型"example2"$some_object

你知道我怎样才能做到这一点吗?

<?php

    class example1{

        private $id;
        private $example2;
        function __construct($id,$some_object){
            $this->id = $id;
            $this->object = $some_object;
        }

        function do_something(){
            $this->example2->moep(); 
        }

    }
    class example2{
        public function moep(){
            print("MOEP!!!");
        }
    }
?>

【问题讨论】:

    标签: php function arguments


    【解决方案1】:

    是和不是。

    PHP5 中有一些类型提示,但它不允许标量类型。所以对于intstring 来说不是,但对于其他几乎所有东西都是肯定的(包括array,很奇怪)。

    见:http://php.net/manual/en/language.oop5.typehinting.php

    【讨论】:

    • 非常感谢!我将仔细研究提示。
    【解决方案2】:

    你有类型提示:http://php.net/manual/en/language.oop5.typehinting.php

    但是,引用手册:

    类型提示不能用于标量类型,例如 int 或 string。
    特征也是不允许的。

    【讨论】:

    • 标量类型提示可能会包含在 php 5.5 中。已经讨论过将它们包含在 5.4 中。
    【解决方案3】:

    在 php 中,您只能键入提示对象(和数组)。您不能输入提示标量:

    http://php.net/manual/en/language.oop5.typehinting.php

    【讨论】:

      【解决方案4】:

      检查构造函数中的类型并在需要时抛出异常:

      function __construct($id,$some_object){
          if (!is_int($id)) throw new UnexpectedValueException("Argument 1 must be an integer");
          if (!is_object($some_object)) throw new UnexpectedValueException("Argument 2 must be an instance of any object");
      
          $this->id = $id;
          $this->object = $some_object;
      }
      

      【讨论】:

      • 这个也很有帮助..非常感谢:)
      猜你喜欢
      • 2020-06-03
      • 2018-03-24
      • 2021-01-10
      • 2017-04-12
      • 2012-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-22
      相关资源
      最近更新 更多