user745235
user745235

Reputation:

PHP class method return type

Is it possible to define the return type like this?

public static function bool Test($value)
{
      return $value; //this value will be bool
}

Upvotes: 35

Views: 52119

Answers (12)

bg117
bg117

Reputation: 362

Yes, you can cast it to bool.

public static function something($value) {
    return (bool)$value;
}

Although from PHP 7, you can explicitly force a return type:

public static function something($value) : bool {
    return $value;
}

Upvotes: 3

Ejaz UL Haq
Ejaz UL Haq

Reputation: 81

The PHP 7.0 introduced return type declaration, so you can use like following:

public static function Test($value): bool  {
  return $value; //this value will be bool
}

For details visit the official documentation.

https://www.php.net/manual/en/language.types.declarations.php

https://wiki.php.net/rfc/return_types

Upvotes: 0

domsson
domsson

Reputation: 4691

Since this question still comes up in search engine results, here is an up-to-date answer:

PHP 7 actually introduced proper return types for functions / methods as per this RFC.

Here is the example from the manual linked above:

function sum($a, $b): float {
    return $a + $b;
}

Or, in a more general notation:

function function_name(): return_type {
    // some code
    return $var // Has to be of type `return_type`
}

If the returned variable or value does not match the return type, PHP will implicitly convert it to that type. Alternatively, you can enable strict typing for the file via declare(strict_types=1);, in which case a type mismatch will lead to a TypeError Exception.

Easy as that. However, remember that you need to make sure that PHP 7 is available on both, your development and production server.

Upvotes: 81

Rehmat
Rehmat

Reputation: 5071

Since PHP 7.0, you can declare the return type like this:

function returnABool(): bool {
    return false;
}

Not only common data types, you can return expected object instances as well. For example you expect a function to always return an instance of a class. This can be achieved like this:

class Biography {
    public function name() {
        return 'John Doe';
    }
}

Now you can declare the return type for this object like this:

function get_bio(): Biography {
    return new Biography();
}

When the function or method returns an unexpected data type, a TypeError is thrown. Here is an example where you will encounter a TypeError.

class Biography {
    public function name() {
        return 'John Doe';
    }
}

class Bio2 {
    public function name() {
        return 'John Doe';
    }
}

function get_bio(): Biography {
    return new Bio2;
}

And an example that will not throw any TypeError:

class Biography {
    public function name() {
        return 'John Doe';
    }
}

class Bio2 {
    public function name() {
        return new Biography();
    }
}

function get_bio(): Biography {
    $bio2 = new Bio2;
    return $bio2->name();
}

More details on declaring return data types for functions and methods can be learnt from the official documentation.

Upvotes: 4

Marcus Lind
Marcus Lind

Reputation: 11440

Since the release of PHP7 they have now introduced Return Type Declarations to PHP.

You define the return type by appending : type when you define the function:

public function foo() : array
{
    return array();
}

Default Weak Mode

By default PHP uses the Weak mode. The documentation explains it in the following way:

In the default weak mode, returned values will be coerced to the correct type if they are not already of that type

For example, see the following example where the function returns a string, even though the defined return type is int

function myInt() : int {
    return "1";
}

echo gettype(myInt());
// Output is "integer"

Strong/Strict Mode

You can also tell PHP to enter strict/strong mode when handling return types by setting declare(strict_types=1). What this means is that PHP will throw a TypeError if a function returns the wrong type. The PHP documentation explain it in the following way:

In strong mode, the returned value must be of the correct type, otherwise a TypeError will be thrown.

declare(strict_types=1);
function myInt() : int {
    return "1";
}

echo gettype(myInt());
// Throws an TypeError

Upvotes: 4

DhruvPathak
DhruvPathak

Reputation: 43235

As per this page : http://php.net/manual/en/language.types.type-juggling.php

You can try doing,

return (boolean) $value;

Now PHP offer return type declaration from PHP 7. I have explained how to use return type in PHP

Upvotes: 9

Adil
Adil

Reputation: 1038

Return type added in PHP 7 ;)

https://wiki.php.net/rfc/return_types

Upvotes: 6

jmblackmer
jmblackmer

Reputation: 1257

Another thing you can do to ensure that overrides don't change the return type, is to do something like this:

public function Test($value)
{
      return (bool) OnTest();
}

private function OnTest($value)
{
      return $value;
}

By doing this, you can allow classes that inherit from your class to change the functionality in OnTest, but still ensure that Test returns a bool value.

Upvotes: 0

Achilleterzo
Achilleterzo

Reputation: 742

Not at the moment in PHP 5 or below, you can define type in function sign but not in the return value. Strict declarations are in mind on PHP ver. 6 and above, but are not implemented yet.

Maybe with some tricks you can do this, like casting before returning the value...

Upvotes: 0

James Booker
James Booker

Reputation: 108

If you know the type of the returned value will be bool, then there's no point casting it within the function.

There is no way to define the return type of a function within PHP as it is loosely-typed. You will have to do your validation within the calling function.

Upvotes: 0

Jeff Parker
Jeff Parker

Reputation: 7507

It's not possible to explicitly define the return type at the method/function level. As specified, you can cast in the return, so for example ...

return (bool)$value;

Alternatively, you can add a comment in phpDoc syntax, and many IDEs will pick up the type from a type completion perspective.

/**
 * example of basic @return usage
 * @return myObject
 */
function fred()
{
    return new myObject();
}

Upvotes: 19

Jason
Jason

Reputation: 15358

PHP doesn't let you do that, instead you can do this:

public static function Test($value)
{
      return (bool) $value; //this value will be bool
}

To my knowledge, you can't use an interface to force a return type

Upvotes: -1

Related Questions