I defined a new variable in __construct()
and I want to use it in another function
of this class
.
But my variable is empty in the other function!
this is my code:
class testObject{
function __construct() {
global $c;
$data = array("name"=>$c['name'],
"family"=>$c['family']);
}
function showInfo() {
global $data;
print_r($data);
}
}
You can do this way. Instead of declaring
$data
asglobal
variable declare aspublic
orprivate
orprotected
variable inside the class depending on your use. Then set the data inside_construct
.Using global inside a class is not a good method. You can use class properties.
Declare variable
$data
as global inside the constructor:Then, it will be visible in other function as well.
Note that extensive usage of global variables is strongly discouraged, consider redesigning your class to use class variables with getters+setters.
A more proper way would be to use
Also, consider separating data fields into separate class variables, as follows. Then you have a typical, clean data class.
And you can even construct this object with data from you global variable
$c
until you elimitate it from your code: