Christian Bundgaard Christian Bundgaard - 2 months ago 9
Ini Question

Declare protected variable inside PHP class with variable from outside

I am using adLDAP plugin (not really relevant), and there's a standard PHP class. Inside this class there's 2 protected variables (admin user and admin password).

I need to declare these two variables with data from an .ini file, that I load with parse_ini_file. How do I do this? I can't get it to work. Example:

$ini_array = parse_ini_file("somefile");
// username comes like $ini_array["php_value ad.username"]
class someClass {
protected $adminUSER = "";
protected $adminPW = "";
}

Answer

Use setters this way:

class someClass
{
    protected $adminUSER = "";
    protected $adminPW = "";

    public function setAdminUser($adminUser)
    {
        $this->adminUSER = $adminUser ;
    }

    public function setAdminPw($adminPW)
    {
        $this->adminPW= $adminPW;
    }
}

$classInstance = new someClass();
$classInstance->setAdminUser('AdminUser');
$classInstance->setAdminPw('AdminPw');

And if you can't modify your class, use heritage:

class myClass extends someClass
{
    public function __construct($adminUser, $adminPW)
    {
        $this->adminUSER = $adminUser ;
        $this->adminPW= $adminPW;
    }
}

$myInstance = new myClass('UserAdmin', 'Password);

Or both heritage and setters... Or simply inherit and read the configuration in the constructor:

class myClass extends someClass
{
    public function __construct()
    {
        $ini_array = parse_ini_file("somefile");
        $this->adminUSER = $ini_array['adminUser'] ;
        $this->adminPW= $ini_array['adminPassword'];
    }
}

Then call your new class, it should be auto-initialized:

$myInstance = new myClass();