Is it possible to initialize a variable in the constructor without creating an instance of the class? For example :

class Class { private $value public function __construct ($val){ $this->value = $val } /** * @Route("/", methods="POST") */ public function get(){ echo $this->value; } } 
  • 2
    As it is interesting, you imagine the PLO. without creating an instance of a class, you basically are missing $this , so your "for example" is not at all clear. - teran
  • @teran, I got my hands on a strange code (working) in which the situation looks exactly like this. I try to understand how the $value variable is initialized in it. I wanted to make sure that knowledgeable people do not in this part of the code whether it happens “somehow”. I will look further - HegoJune
  • @HegoJune, list all the code. the current code is just a class description. - Chad
  • получил на руки странный код (работающий) в котором ситуация выглядит именно так. try this: $c = new Class1(1); $c->__construct(2); var_dump($c->get()); $c = new Class1(1); $c->__construct(2); var_dump($c->get()); . In addition, there may be traits, inheritance. After all, you are watching the wrong file. Use the Reflection API to examine the object. Well __wakeup - Total Pusher

1 answer 1

No you can not. A constructor creates an instance of a class, without creating it, it is impossible to invoke a constructor. Look towards static variables.

  • It seems to me or it should be "... impossible to call a method" and not a constructor? - teran
  • Why? The variable wants to be created, according to the question, in the constructor. And here are the methods? - Chad
  • then I am somewhat embarrassed that your sentence begins and ends with the word Constructor. oil-oil - teran
  • The body of the constructor is called at the time the class is instantiated. Accordingly, it is impossible to initiate a variable in the constructor without creating an instance of the class. - Chad