开发者

php4 - Should i use global variables in this case?

<?php
    global $words;

    class A {

        function say()
        {
            global $words;
            $words =开发者_StackOverflow中文版 'man';
            A::hello();
            A::bye();

            echo $words;
        }

        function hello(){
            global $words;
            $words .= 'hello';
        }

        function bye(){
            global $words;
            $words .= 'bye';
        }

    }
    A::say();
?>

i think it is stupid, Can you pointed me a good way ?


Declare $words as a static variable within the class:

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();


PHP4 code (compatible with 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();

In general, you do not want to use the global keyword when doing OOP. Pass any dependencies through the ctor or via appropriate setters. Relying on globals will quickly introduce side effects into your application, breaks encapsulation and will make your API lie about it's dependencies. You should also avoid all static classes because they will tightly couple the calling class to the static class. This makes maintenance and testing more painful than it needs to be (same for globals).

Also see https://secure.wikimedia.org/wikipedia/en/wiki/Solid_(object-oriented_design)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜