在其他方法中使用__construct()中的变量 [英] Use a variable from __construct() in other methods
问题描述
我在 __ construct()
中定义了一个新变量,并且我想在另一个函数
中使用它类
。
但是我的变量在其他函数中是空的!
这是我的代码:
class testObject {
function __construct(){
global $ c;
$ data = array(name=> $ c ['name'],
family=> $ c ['family']);
}
函数showInfo(){
global $ data;
print_r($ data);
}
}
函数__construct(){
global $ c;
全球$数据;
$ data = array(name=> $ c ['name'],
family=> $ c ['family']);
}
然后,它也会在其他函数中显示。注意广泛使用全局变量是强烈不鼓励的,考虑重新设计你的类,使用类变量和getters + setter。
更正确的方法是使用
class testObject
{
private $ data;
函数__construct(array $ c)
{
$ this-> data = array(
name=> $ c ['name']] ,
family=> $ c ['family']
);
函数showInfo()
{
print_r($ this-> data);
$ b $ // getter:如果你需要访问这个类以外的数据
function getData()
{
return $ this->数据;
$ b 另外,请考虑将数据字段分隔为不同的类变量,如下。然后你有一个典型的,干净的数据类。
class testObject
{
private $ name;
私人$家庭;
函数__construct($ name,$ family)
{
$ this-> name = $ name;
$ this-> family = $ family;
}
函数showInfo()
{
print(name:。$ this-> name。,family:。$ this-> ;家庭);
}
// getters
function getName()
{
return $ this-> name;
}
函数getFamily()
{
return $ this-> family;
}
}
你甚至可以构造这个对象从你的数据全局变量 $ c
,直到你从你的代码中取消:
new testObject($ c ['name'],$ c ['family'])
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);
}
}
解决方案 Declare variable $data
as global inside the constructor:
function __construct() {
global $c;
global $data;
$data = array("name"=>$c['name'],
"family"=>$c['family']);
}
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
class testObject
{
private $data;
function __construct(array $c)
{
$this->data = array(
"name"=>$c['name'],
"family"=>$c['family']
);
}
function showInfo()
{
print_r($this->data);
}
// getter: if you need to access data from outside this class
function getData()
{
return $this->data;
}
}
Also, consider separating data fields into separate class variables, as follows. Then you have a typical, clean data class.
class testObject
{
private $name;
private $family;
function __construct($name, $family)
{
$this->name = $name;
$this->family = $family;
}
function showInfo()
{
print("name: " . $this->name . ", family: " . $this->family);
}
// getters
function getName()
{
return $this->name;
}
function getFamily()
{
return $this->family;
}
}
And you can even construct this object with data from you global variable $c
until you elimitate it from your code:
new testObject($c['name'], $c['family'])
这篇关于在其他方法中使用__construct()中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!