2016-02-18 11 views
14

私は特別に「無効」PHP7での戻り値の型、との問題を抱えています。PHP7 voidを返す型が動作していませんか?

それは他のすべてのタイプ、int型、文字列は、null、ブール値、クラスオブジェクトで動作します。

しかし、私がvoidを使用する場合には、オブジェクトボイドのインスタンスを返すために私を期待したが、実際にそれが何のためにあるのか、ボイドのthatsとして任意のリターンを期待すべきではありません。

注:私はここにPHP 7.0.3

を実行しているコードです:

public static function setResponseCode(int $code) : void 
    { 
     http_response_code($code); 

    } 

とエラーメッセージは次のとおりです。

Uncaught TypeError: Return value of CodeBase\HttpRequester::setResponseCode() must be an instance of void, none returned in /var/www/html/src/HttpRequester.php:86 Stack trace: #0 /var/www/html/index.php(103): CodeBase\HttpRequester::setResponseCode(500) #1 {main} thrown in /var/www/html/src/HttpRequester.php on line 86

+1

てみてください;'有効です。'http_response_code'が値を返すので、おそらく混乱して結果が返されていると思うかもしれません。 – RiggsFolly

+3

@RiggsFollyまたはvoid戻り値の型としてそのようなものはありません:) – PeeHaa

+0

@PeeHaaはい忘れてしまいましたRFC Docs – RiggsFolly

答えて

21

ボイドの戻り値の型は、PHP 7.1のためのものです(これはあなたがこれを尋ねたときにまだリリースされていなかった)。 From the RFC

Version: 0.2.1
Date: 2015-02-14 (v0.1, later withdrawn), 2015-10-14 (v0.2, revival)
Author: Andrea Faulds, [email protected]
Status: Implemented (PHP 7.1)

-4

理由だけではなく、それは空と同じである

function printLn($a) { 
    echo $a; 
    return;} 

を使用していません。

あなたも、私はちょうどここに答え見つけた

+4

なぜですか?戻り値の型宣言の考え方は、その関数内の他の型の変数を返すことを避けることです。別のプログラマがいくつかのパラメータを混ぜて、何を望むものを返そうとしたらどうでしょうか? –

7

ませまで、存在しませんPHP 7.1。 PHP 7.0のために、あなたはvoid関数/メソッドのために完全に戻り値の型を省略しなければなりません。

function printLn($a) { 
    echo "$a\n"; 
} 

は残念ながら、あなたは、この関数/メソッドには型の安全性を持っていない、とあなたはそれから何かを返す開始した場合に何TypeErrorはスローされません。

幸いにも、PHP 7.1 fixes this

Support for a new void return type is added. It requires that a function not return any value.

これはPHP 7.1の正しい構文である:これはthe proposal that created return type hints中に延期された

function should_return_nothing(): void { 
    return 1; // Fatal error: A void function must not return a value 
} 

We keep the current type options. Past proposals have suggested new types such as void, int, string or scalar; this RFC does not include any new types. Note that it does allow self and parent to be used as return types. ...

Future Work

Ideas for future work which are out of the scope of this RFC include:

  • Allow functions to declare that they do not return anything at all (void in Java and C)

NULLはまた、nが戻り値の型として許可されています。

1

TL; DR

戻り型がvoid作品すでに利用可能であるPHP 7.1以降。構文作業

です: `リターンを追加

<?php 
function procedure(): void 
{ 
// return 'will not work'; 
} 

echo procedure(); 
関連する問題