Good.
I have a class attribute that I want to initialize with another static attribute of the same class, the problem is that none of the ways I have tried assigning the value to it work. This is the code I have:
<?php
class ClaseEjemplo {
public static $name = "santiago";
//protected $asd = self::$name; //No funciona
//protected $asd = static::$name; //No funciona
//protected $asd = ClaseEjemplo::$name; //No funciona
//protected $asd = ClaseEjemplo::$name; //No funciona
//protected $asd = ClaseEjemplo::name; //No funciona
protected $asd;
// esto si funciona
///*
function __construct(){
$this->asd = self::$name;
} //*/
}
$clase = new ClaseEjemplo;
var_dump($clase);
I know that with the constructor it can be initialized, but I wonder if it can be initialized just by assigning it.
To test the code I use this sandbox
You can't do that with a static variable. Since its value is assigned at run time, you would be making both variables compete. The order in which you declare them does not imply that when you assign the value of
$asd
you already have previously assigned$name
.But , what you want can be done with a class constant :
Check it out in the sandbox .
Taking into account your comment , I will tell you that the constructors are, precisely, to initialize classes; if you have a class that inherits from another (as is the case) and you need to set a value at instantiation time, it makes sense to do so in the constructor.