问题描述:

How do i use/assign a defined variable in my config file to a member variable of the class without using the constructor method like below

require('config.php');

class MyClass{

public $email=MY_EMAIL_FROM_CONFIG;

function MyClass(){

}

....

}

this direct assignment gives me a error, any other ways ? OR any explanation why this has been not allowed in PHP ?

网友答案:

config.php

define('EMAIL',  '[email protected]');

MyClass.php

require('config.php');
class MyClass{

    public $email= EMAIL;

    function myFunction(){

    }
    ....    
}

You might not need the constant to be assigned to a variable since it can be accessed anywhere within the class

网友答案:

code-jaff has the correct solution. I have another one (almost the same).

config.php

$_CONFIG = Array(
 "email" => "[email protected]", 
 "host" => "example.com",
 ...
);
define("CONFIG", $_CONFIG);

myclass.php

require('config.php');
class MyClass{

    public $email= CONFIG["email"];

    function myFunction(){ }
}
相关阅读:
Top