mysql - php global within a class but outside a function? -


I can do $ conn from within my function such as:

  function Xyz ($ A) {global $ conn; ....}   

I am thinking that this is a way of doing a class before.

  class abc {global $ conn; Public function xyz ($ a) {$ conn- & gt; Execute ...} public function xya ($ a) {$ conn- & gt; Execute ...}} The above method gives me an error I know that I can get it this way:  
  class ABC {Public Function xyz ($ a) {global $ conn; $ Conn- & gt; Execute ...} Public Function xya ($ a) {global $ conn; $ Conn- & gt; Execute ...}}   

I hope you can understand what I mean. Thanks in advance for the help.

Your second example is possible, your first is not. There is no such thing as a member of a class variable that is a global variable, or the use of scope like yours is your first example. Generally, however, I would advise to avoid global use. Keyword I absolutely do a lot of PHP programming and have never used it in serious (actually, nothing in the last 10 or so years). .

If you need to be able to use a variable in your class, I will pass the variable to my class constructor, such as: class ABC { Private $ Con; Function __ conversion ($ conn) {$ this- & gt; Conn = $ conn; } Public function xyz ($ a) {$ this- & gt; Conn- & gt; carry about (); } Public Function xya ($ a) {$ this- & gt; Conn- & gt; carry about (); }}

Then you will have

  $ myabc = new abc ($ conn);   

In this way, you are making clear which function is available for what variable. It makes it possible / easy in the future to rename different classes of different values ​​of the $ cone or even rename, and still you go through all your classes and every reference in that context Will have to change.

With global variables, it is very difficult to track which function is available for variables, or does it in a structured manner. Apart from this, more dependencies on the global variable, unless you lose the benefits of having classes, there is more temptation to tighten.

Comments

Popular posts from this blog

mysql - BLOB/TEXT column 'value' used in key specification without a key length -

c# - Using Vici cool Storage with monodroid -

python - referencing a variable in another function? -