Suppose I have a php file along these lines:
<?php function abc() { } $foo = 'bar'; class SomeClass { } ?>
Is there anything special I have to do to use abc()
and $foo
inside SomeClass
? I'm thinking along the lines of using global
in a function to access variables defined outside the function.
(I'm new to OOP in PHP)
If you want to use that variable even outside the class, you must declared that variable as a global. Then the variable can be accessed using its name inside and outside the class and not using the instance of the class. class Geek: # Variable defined inside the class.
Yes you can definitely have functions outside of a class.
To access a variable outside a function in JavaScript make your variable accessible from outside the function. First, declare it outside the function, then use it inside the function. You can't access variables declared inside a function from outside a function.
Public member variables and functions are accessible outside of the class. For example, you can change the values of variables through statements or functions outside of the class and you can call functions within the class from statements or other functions outside of the class.
functions outside any class are global an can be called from anywhere. The same with variables.. just remember to use the global for the variables...
e.g
<?php function abc() { } $foo = 'bar'; class SomeClass { public function tada(){ global $foo; abc(); echo 'foo and '.$foo; } } ?>
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.
<?php function abc() { } $foo = 'bar'; class SomeClass { private $foo; public function __construct($foo) { $this->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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With