If I have two public functions and I want to pull a variable from one inside of another, what is the best way to accomplish this? I know about ‘global’ but this method seems like it could cause me problems down the road.
Imagine I have something like this:
class myCMS {
public function process_apples() {
$a = $_POST['$apples'];
}
public function display_apples() {
echo $a;
}
}
How would I go about using display_apples() to report $a from process_apples()? Im new to PHP, so feel free to let me know if I am violating some best practicing for organizing my code.
If you have two methods in a class, and want a variable to shared between them, you should use a class property — which is kind of a variable that’s inside a class.
Your class would then look like this :
And a couple of notes :
$this->property_nameto access a property$_POSTfrom inside your class : it makes your class dependent on external global variables — of course, up to you to determine whether it’s a problem or not.