添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Return types in PHP refer to the type of data returned by a function in PHP. In strongly typed languages like JAVA, every function must have a return type but it is optional in PHP as it is a loosely typed programming language. It is a good practice to include return types as it reduces ambiguity, limits error and improves code quality.

We will be looking into several return types in PHP. Without any further ado, let's dive in.

This is a PHP directive that enforces strict typing. It is used to ensure that only values of the expected data type are passed to a function or method.

When strict_types is set to 1, PHP will require that function arguments are of the correct data type. If an argument is of the wrong type, PHP will throw a TypeError instead of attempting to convert the argument to the expected type.

With this in place, we can be rest assured PHP is not doing any type conversion that we may not be aware of when incorrect types are used.

The type of data we want the function or method to return is declared by putting a colon and the type between the closing parenthesis and the opening curly bracket.

class Arithmetic { public function __construct ( public int $a , public int $b ) {} public function addition (): int { $sum = $this -> a + $this -> b ; return $sum ; echo ( new Arithmetic ( 12 , 20 )) -> addition (); Enter fullscreen mode Exit fullscreen mode

The string is a return type used to represent text. It can contain any sequence of characters, including letters, numbers, symbols, and whitespace.

Strings can be declared using a single or double quote.
public function __construct ( public string $message ) {} public function greeting (): string { return $this -> message ; echo ( new Greeting ( "Good day fellow!" )) -> greeting (); Enter fullscreen mode Exit fullscreen mode

bool , short for "boolean", is a return type used to represent logical values. A bool variable can only have two possible values: true or false.

It is important to note that PHP returns 1 for true and nothing for false .
function playlist (): array { return [ 'Diced Pineapple' , 'Formation' , 'Thinking Out Loud' ]; print_r ( playlist ()); function user (): array { return [ 'name' => 'John' , 'age' => 25 , 'location' => 'New York' ]; print_r ( user ()); Enter fullscreen mode Exit fullscreen mode class Playlist { public function music (): array { return [ 'Diced Pineapple' , 'Formation' , 'Thinking Out Loud' ]; public function user (): array { return [ 'name' => 'John' , 'age' => 25 , 'location' => 'New York' ]; print_r ( ( new Playlist ) -> music () print_r ( ( new Playlist ) -> user () Enter fullscreen mode Exit fullscreen mode function earth (): void { $title = "This planet supports life" ; $age_in_years = 4_800_000_000 ; earth (); Enter fullscreen mode Exit fullscreen mode class Planet { public function earth (): void { $title = "This planet supports life" ; $age_in_years = 4_800_000_000 ; ( new Planet ) -> earth (); Enter fullscreen mode Exit fullscreen mode

A mixed return type is used to indicate that a function or method may return different data types, depending on the input or the logic within the function. This is helpful when you cannot determine the exact return type ahead of time, or when the return type is dependent on a complex set of conditions.
function getMultiplier ( int $factor ): callable { return function ( int $number ) use ( $factor ) { return $number * $factor ; $multiplyByTwo = getMultiplier ( 2 ); echo $multiplyByTwo ( 5 ); $multiplyByThree = getMultiplier ( 3 ); echo $multiplyByThree ( 6 ); Enter fullscreen mode Exit fullscreen mode public function __construct ( public int $factor ) {} public function getMultiplier (): callable { return function ( int $number ) { return $number * $this -> factor ; $multiplyByTwo = ( new Multiplier ( 2 )) -> getMultiplier (); echo $multiplyByTwo ( 5 ); $multiplyByThree = ( new Multiplier ( 3 )) -> getMultiplier (); echo $multiplyByThree ( 6 ); Enter fullscreen mode Exit fullscreen mode function openFile ( string $filename ): resource { $file = fopen ( $filename , "r" ); if ( ! $file ) { throw new Exception ( "Failed to open file: $filename " ); return $file ; Enter fullscreen mode Exit fullscreen mode public function openFile ( string $filename ): resource { $file = fopen ( $filename , "r" ); if ( ! $file ) { throw new Exception ( "Failed to open file: $filename " ); return $file ; Enter fullscreen mode Exit fullscreen mode

Classes can also be a return type. In this example, the Zoo class has a method called getAnimal() that returns an object of the Animal class. The return type of this method is specified as Animal using the :Animal syntax after the method signature. This means the return type will be a type of Animal class or any of its subclasses.
class Animal { public function __construct ( public string $name , public int $age ) {} function getAnimal (): Animal { return new Animal ( "Leo" , 5 ); print_r ( getAnimal ()); Enter fullscreen mode Exit fullscreen mode class Animal { public function __construct ( public string $name , public int $age ) {} class Zoo { public function getAnimal (): Animal { return new Animal ( "Leo" , 5 ); print_r (( new Zoo ()) -> getAnimal ()); Enter fullscreen mode Exit fullscreen mode class Address { public function __construct ( public string $street , public string $city , public string $state ) {} class Person { public function __construct ( public string $name , public Address $address ) {} public function getAddress (): object { return $this -> address ; $address = new Address ( "123 Main St" , "Anytown" , "CA" ); $person = new Person ( "John Doe" , $address ); $addressObj = $person -> getAddress (); Enter fullscreen mode Exit fullscreen mode

What if we can not tell the actual type a class should return or do we want to intentionally make the return type for any class dynamic?

PHP allows us to include additional return types using the union type, this allows us to include alternate types by separating them with a pipe | .

Return types are an important feature in PHP that allows developers to specify the type of value that a function should return. By declaring a return type, PHP can ensure that the value returned by a function is of the expected type, which can help prevent errors and improve code quality.

In PHP 7 and later versions, developers can use several different types of return types, including scalar types like int, float, and string, as well as compound types like array and callable. Additionally, PHP 8 introduced new return types, including union types and mixed types, which provide even more flexibility for developers.

Type declarations in PHP can be used not only for return types but also for parameter types and class properties. Type declarations can help prevent type errors, improve code readability, and make code easier to maintain.

Built on Forem — the open source software that powers DEV and other inclusive communities.

Made with love and Ruby on Rails . DEV Community © 2016 - 2024.