The warning is telling you that there is a property you are trying to set which isn't listed at the top of the class.
When you run this:
class database {
public $username = "root";
public $password = "pasword";
public $port = 3306;
public function __construct($params = array())
{
foreach ($params as $key => $value)
{
$this->{$key} = $value;
}
}
}
$db = new database(array(
'database' => 'db_name',
'server' => 'database.internal',
));
It is roughly equivalent to this:
class database {
public $username = "root";
public $password = "pasword";
public $port = 3306;
}
$db = new database;
$db->database = 'db_name';
$db->server = 'database.internal';
The warning is that there is no line in the class definition saying that $db->database
or $db->server
exist.
For now, they will be dynamically created as untyped public properties, but in future, you will need to declare them explicitly:
class database {
public $database;
public $server;
public $username = "root";
public $password = "pasword";
public $port = 3306;
public function __construct($params = array())
{
foreach ($params as $key => $value)
{
$this->{$key} = $value;
}
}
}
$db = new database(array(
'database' => 'db_name',
'server' => 'database.internal',
));
In some rare situations, you actually want to say "the properties of this class are whatever I decide to add at run-time"; in that case, you can use the #[AllowDynamicProperties]
attribute, like this:
#[AllowDynamicProperties]
class objectWithWhateverPropertiesIWant {
public function __construct($params = array())
{
foreach ($params as $key => $value)
{
$this->{$key} = $value;
}
}
}