Home > Backend Development > PHP Tutorial > php: Can a constructor return a value?

php: Can a constructor return a value?

黄舟
Release: 2023-03-12 10:30:02
Original
4235 people have browsed it

php: ConstructorCan return a value?

class a
{
    function construct()
    {
            return 'abc';
     }
}
Copy after login

Can I?

It seems that it is not possible,,, I forgot, I don’t have much idea about this

You can write it like this, but after new, you still get the object of this class

Why do you use it this way? ?

If you want to have a function that returns abc, you only need to write another one and call it once.

No!
The function of the constructor is mainly used to define the initialized state when the object of the class is created. It has no return value and cannot be modified with void.

Constructors are all used Regarding the initialization data, the data can only enter but not exit

Damn, this kind of question still needs to be asked. I really don’t know how to write a test example to see if it’s done

It is not possible to get or return some values ​​in the constructor, but writing a function with the same name as the class name can achieve this goal.

class abc
{
  public $var1;
  public $var2;
   private function abc($var1,$var2)
   {
     $this->var1=$var1;
     $this->var2=$var2;
   }
}
......
......
$abc=new abc(123,'abc');
var_dump($abc);
Copy after login

But writing a function with the same name as the class name can achieve this goal
What does it mean? ? ?
Isn’t the function with the same name as the class name the constructor? ?

Have you ever seen a new object return values ​​of other types? ? new returns an object, so no matter what you manually return in the constructor, it is an object.

The above is the detailed content of php: Can a constructor return a value?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template