PHP class: Global variable as property in class

后端 未结 7 1164
囚心锁ツ
囚心锁ツ 2020-12-05 13:03

I have a global variable outside my class = $MyNumber;


How do I declare this as a property in myClass?
For every method in my class, this is what

7条回答
  •  天涯浪人
    2020-12-05 13:49

    Simply use the global keyword.

    e.g.:

    class myClass() {
        private function foo() {
            global $MyNumber;
            ...
    

    $MyNumber will then become accessible (and indeed modifyable) within that method.

    However, the use of globals is often frowned upon (they can give off a bad code smell), so you might want to consider using a singleton class to store anything of this nature. (Then again, without knowing more about what you're trying to achieve this might be a very bad idea - a define could well be more useful.)

提交回复
热议问题