<?php
global $words;
class A {
function say()
{
global $words;
$words = 'man';
A::hello();
A::bye();
echo $words;
}
function hello(){
global $words;
$words .= 'hello';
}
function bye(){
global $words;
$words .= 'bye';
}
}
A::say();
?>
我认为这很愚蠢,你能指出我一个好方法吗?
答案 0 :(得分:2)
将$words
声明为类中的静态变量:
class A {
static $words;
static function say() {
self::$words = 'man';
A::hello();
A::bye();
echo self::$words;
}
static function hello() {
self::$words .= 'hello';
}
static function bye() {
self::$words .= 'bye';
}
}
A::say();
答案 1 :(得分:1)
PHP4代码(与PHP5兼容)。
class A {
var $words;
function A($words) {
$this->words = $words;
}
function say() {
$this->words = 'man';
$this->hello();
$this->bye();
return $this->words;
}
function hello() {
$this->words .= 'hello';
}
function bye() {
$this->words .= 'bye';
}
}
$a = new A($words);
echo $a->say();
一般来说,you do not want to use the global
keyword when doing OOP。 Pass any dependencies through the ctor or via appropriate setters。依赖全局变量会很快将副作用引入您的应用程序,打破封装并使您的API依赖于它的依赖性。 You should also avoid all static classes因为它们会将调用类紧密地耦合到静态类。这使得维护和测试比它需要的更痛苦(全局变量相同)。
另见https://secure.wikimedia.org/wikipedia/en/wiki/Solid_(object-oriented_design)