-1

See the below code to understand. Please explain when i should use this mechanism in oop.

class A
{
}

class B
{
    public function foo(): A
    {
    }
}
Mahedi Hasan Durjoy
  • 1,031
  • 13
  • 17

1 Answers1

1

In your code, the foo() function of class B has to return an object type of Class A, otherwise, an exception will be thrown. We can define the return type of a PHP function by using the below syntax.

function foo(): int
{
    return 11;
}
function bar(): Baz
{
    return new Baz();
}

If you run your code as below-

<?php 

class A
{
}

class B
{
    public function foo(): A
    {
    }
}

$b = new B();
echo $b->foo();

?>

Output will be-

Fatal error: Uncaught TypeError: B::foo(): Return value must be of type A, none returned in D:\xampp\htdocs\test.php:16 Stack trace: #0 D:\xampp\htdocs\test.php(20): B->foo() #1 {main} thrown in D:\xampp\htdocs\test.php on line 16

This ensures strict typing in PHP. I Hope, you have understand the answer. You can read more about why you should use strict typing here https://dzone.com/articles/strong-typing-really-needed

arafatkn
  • 117
  • 4