X
X
XenK2015-09-30 10:27:44
PHP
XenK, 2015-09-30 10:27:44

Return in PHP constructor?

There is a code:

class GetInfo {

    public $name;

    function __construct($name) {
        $this->name = $name;
        $name = strtoupper($name);
        
        return $name;      
    }

}

$a = new GetInfo('Ivan');
...

The question is how to get the return itself from the constructor?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
V
Vladislav Soprun, 2015-09-30
@soprun

You need __toString

class GetInfo
{

    public $name;

    function __construct($name)
    {
        $this->name = strtoupper($name);
    }

    function __toString()
    {
        return $this->name;
    }

}

$a = new GetInfo('Ivan');

// ...

I
Igor Makarov, 2015-09-30
@onqu

The constructor does not return a value.
Signature:
Read php.net/manual/ru/language.oop5.decon.php

C
Cat Anton, 2015-09-30
@27cm

If you really want to: https://3v4l.org/iOpXc
echo $a->__construct('Ivan');

D
Dmitry, 2015-09-30
@mytmid

Since PHP 5.4
, you can use the following code:

Class A
{
    
    private $msg;
    
    public function __construct($msg)
    {
        $this->msg = $msg;
    }
    
    public function getMsg()
    {
        return 'Hello, ' . $this->msg;
    }

}


$msg =  (new A('World!'))->getMsg();

echo $msg; // выведет Hello, World!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question