A
A
Anatoly Tsybin2020-10-17 00:21:58
PHP
Anatoly Tsybin, 2020-10-17 00:21:58

How, when creating a class object using the load method, add the value of its property without ___construct?

There is a class myClass, the load method must create an object of this class and set the value of the $property property.
If just return(new myClass()) - an object is created with the value $property = null.
If return(new myClass())->setProp("4545") - a variable is created with value = null.

class myClass {
     public  $name;
     public  $property;

 public function setName($val){
       $this->name = $val;
     }
      public    function setProp($val){
        $this->property = $val;
    }


     public static function load (){
         return(new myClass())->setProp("4545");

     }
}

$test = new myClass();

$test2=myClass::load();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oleg, 2020-10-17
@Tsybinn

You can modify the method for chain syntax

/**
     * @param $val
     * @return $this
     */
    public    function setProp($val){
        $this->property = $val;
        return $this;
    }

Or be simpler and use a variable in the load method
$instance = new MyClass() ; // Попутно Класс с большой буквы чтобы отличать от объекта созданного из него
$instance->setProp();
return $instance;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question