Stack Overflow Asked by Mahedi Hasan Durjoy on February 13, 2021
See the below code to understand. Please explain when i should use this mechanism in oop.
class A
{
}
class B
{
public function foo(): A
{
}
}
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:xampphtdocstest.php:16 Stack trace: #0 D:xampphtdocstest.php(20): B->foo() #1 {main} thrown in D:xampphtdocstest.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
Answered by arafatkn on February 13, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP