0

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 ?

2
  • I'd more than likely use a method which is available in all scopes. Perhaps look into the function: define() Commented Feb 4, 2014 at 2:13
  • 1
    Where do you get an error, and what does it say? Commented Feb 4, 2014 at 2:17

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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(){ }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.