聲明變量$data
全球的構造函數中:
function __construct() {
global $c;
global $data;
$data = array("name"=>$c['name'],
"family"=>$c['family']);
}
然後,它會在其他功能可看見的。
請注意,廣泛使用全局變量是極不鼓勵的,請考慮重新設計您的類以使用類變量與getters + setter。
更合適的方式是使用
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;
}
}
另外,還要考慮數據字段分成單獨的類變量,如下所示。然後你有一個典型的,乾淨的數據類。
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;
}
}
直到你從你的代碼elimitate它,你甚至可以從你的全局變量$c
構建具有數據這個對象:
new testObject($c['name'], $c['family'])
實際上你看過嗎:http://uk.php.net/manual/en/language.oop5.php? – 2013-04-04 12:32:43
不是答案,而是相關的:http://stackoverflow.com/questions/11923272/use-global-variables-in-a-class/11923384#11923384 – PeeHaa 2013-04-04 12:32:46
使用類屬性而不是'global': http:// www.php.net/manual/en/language.oop5.properties.php使用'global'(幾乎?)從來不是一個好的解決方案。 – str 2013-04-04 12:33:22