Dynamic property creation in PHP is deprecated: warning
P粉797855790
P粉797855790 2023-10-20 10:40:49
1
5
718

I'm seeing this happen more and more, but I'm not sure what I need to do to stop this warning:

DEPRECATED: Creating dynamic properties... DEPRECATED

This is my class:

class database {

    public $username = "root";
    public $password = "password";
    public $port = 3306;

    public function __construct($params = array())
    {
        foreach ($params as $key => $value)
        {
            $this->{$key} = $value;
        }
    }
}

This is how I instantiate it.

$db = new database(array(
    'database' => 'db_name',
    'server' => 'database.internal',
));

This gives me two messages:

DEPRECATED: Create dynamic properties database::$database Deprecated

DEPRECATED: Create dynamic properties database::$server Deprecated


P粉797855790
P粉797855790

reply all(4)
P粉299174094

This warning tells you that the property you are trying to set is not listed at the top of the class.

When you run this command:

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',
));

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 indicating that $db->database or $db->server exists.

Currently, they are dynamically created as untyped public properties, but in the 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 cases you actually want to say "the properties of this class are whatever properties I decide to add at runtime"; in that case you can use #[AllowDynamicProperties] Attributes, as shown below:

#[AllowDynamicProperties]
class objectWithWhateverPropertiesIWant {
    public function __construct($params = array())
    {
        foreach ($params as $key => $value)
        {
            $this->{$key} = $value;
        }
    }
}
  • reply Ah, master
    徐涛 author 2023-10-26 17:53:30
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!