Why can not I declare an attribute as an object?

12

I have a class A and I'm creating a class B . I want one of the attributes of B to be an object of A .

Why is the public $objeto = new A(); notation correct?

    
asked by anonymous 11.07.2017 / 20:06

2 answers

12
  

Because the notation public $ object = new A (); is not correct?

Because language does not allow. As the documentation says, initialization must be the value of a constant, that is, if it is possible to know it at compile time. If this value depends on a function call, that is, an expression, it can not depend on anything that is known at runtime.

  

This declaration may include an initialization, but this initialization must be a constant value - that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

As the other responses commented, the solution to these 'complex' startups is to create a constructor of your own.

This code is invalid because the expression depends on the execution / call / creation of the class at runtime.

class teste{
    static $a;
    static $b = 10;
    static $total = self::$a + self::$b;
}

But this statement works:

class teste{
    static $total = 10 + 51;
}

Recommended reading:

What is a builder for?

    
11.07.2017 / 20:30
2

Only one add-on to the other response, you can only set values such as variables, class instances, and function calls to a class if you use the __constructor method .

In your case.

class B{

   protected $a;

   // Determina que o parâmetro passado será armazenado em 'a'
   // e deve ser uma instância da classe 'A'.
   public function __construct (A $a) {
          $this->a = $a;
   }

   public function getA()
   {
       return $this->a;
   }
}

$a = new A;
$b = new B($a);

In some cases, because it is necessary to add instances of certain classes to one another, the Injection of dependency

    

12.07.2017 / 14:24