0

だから私がクラスを構築すると...

class Foo {
    public $_string;
    public function($sString = 'new string') {
        $this->_string = $sString;
    }
}

$sString は、関数の引数の文字列型であると強制的に言いたいのですが、次のような...

class Foo {
    public $_string;
    public function(string $sString = 'new string') {
        $this->_string = $sString;
    }
}

しかし、私のIDEは「未定義のクラス 'String'」と言い、phpはエラーをスローするので、どのタイプの変数がクラスの関数に渡されているかを強制的に伝える方法はありますか、それともこのように関数内で宣言する必要がありますか? ...

class Foo {
    public $_string;
    public function($sString = 'new string') {
        $this->_string = (string)$sString;
    }
}

任意の助けをいただければ幸いです。ありがとうございました。

4

3 に答える 3

2

Not today. PHP 5.4 may have a scalar type-hint, but this has been proposed subsequently dropped before.

All you can do is an is_string() check in the body.

于 2013-03-12T03:33:57.453 に答える
1

What you're describing is "type hinting" and PHP supports it, however (for some reason) it does not allow it for any of the built-in intrinsic types or string ( http://php.net/manual/en/language.oop5.typehinting.php ) which explains the problem you're having.

You can workaround this by manually calling is_string inside your function, but things like this aren't necessary if you control your upstream callers.

于 2013-03-12T03:34:28.593 に答える
0

you can use is_string function to check it.

if (is_bool($message)) {
  $result = 'It is a boolean';
}
if (is_int($message)) {
  $result = 'It is a integer';
}
if (is_float($message)) {
  $result = 'It is a float';
}
if (is_string($message)) {
  $result = 'It is a string';
}
if (is_array($message)) {
  $result = 'It is an array';
}
if (is_object($message)) {
  $result = 'It is an object';
}

check this.

class Foo {
    public $_string;
    public function($sString = 'new string') {
        if (is_string($sString)) {
           $this->_string = $sString;
        }
    }
}
于 2013-03-12T03:35:46.387 に答える