Accessing variables and methods outside of class definitions

后端 未结 6 1675
盖世英雄少女心
盖世英雄少女心 2020-12-05 11:02

Suppose I have a php file along these lines:


Is there anything sp

6条回答
  •  渐次进展
    2020-12-05 11:18

    Simply pass your variable to object instance through constructor or pass it to method when it's needed and remember to DON'T USE GLOBAL! ANYWHERE!

    Why global is to be avoided?

    The point against global variables is that they couple code very tightly. Your entire codebase is dependent on a) the variable name $config and b) the existence of that variable. If you want to rename the variable (for whatever reason), you have to do so everywhere throughout your codebase. You can also not use any piece of code that depends on the variable independently of it anymore. https://stackoverflow.com/a/12446305/1238574

    You can use abc() everywhere because in PHP functions are globally accessible.

    foo = $foo;
        }
        public function doSomething() {
            abc($this->foo);
        }
    }
    
    class OtherClass {
        public function doSomethingWithFoo($foo) {
            abc($foo);
        }
    }
    
    $obj = new SomeClass($foo); // voillea
    
    // or
    
    $obj2 = new OtherClass();
    $obj2->doSomethingWithFoo($foo);
    

提交回复
热议问题