0

関数に与えられるデータ型を指定したい。

このデモ コード (例として) では、"__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!!!");
        }
    }
?>
4

4 に答える 4

1

タイプヒントがあります: http://php.net/manual/en/language.oop5.typehinting.php

しかし、マニュアルから引用するには:

型ヒントは、int や string などのスカラー型では使用できません。
特性も許可されていません。

于 2012-11-05T14:55:54.747 に答える
1

はいといいえ。

PHP5 にはいくつかの型ヒントがありますが、スカラー型は許可されていません。したがって、intstringにはありませんが、他のほとんどすべて (array奇妙なことに、 を含む) にはあります。

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

于 2012-11-05T14:56:06.987 に答える
0

コンストラクターの型をチェックし、必要に応じて例外をスローします。

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;
}
于 2012-11-05T15:23:49.020 に答える
0

PHP では、ヒント オブジェクト (および配列) のみを入力できます。ヒント スカラーを入力することはできません。

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

于 2012-11-05T14:56:02.853 に答える