TransWikia.com

What is the purpose to use className beside functionName using colon(:)

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
    {
    }
}

One Answer

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

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP