从单独的函数中提取变量

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 :

class myCMS {
    protected $a;   // declare the property (won't be visible from outside the class)

    public function process_apples() {
        $this->a = $_POST['$apples'];
    }

    public function display_apples() {
        echo $this->a;
    }
}


And a couple of notes :

  • You need to use $this->property_name to access a property
  • Not related, but you should generally no use $_POST from 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.

You would have:

class myCMS {

   private $a;

   public function process_apples() {

     $this->a = $_POST['$apples'];
     // process

   }

   public function display_apples() {

     echo $this->a;    
   }
}

Since you're using a class, you could make a private class variable, like this:

class myCMS {
    private $a;

    public function process_apples() {
        $this->a = $_POST['$apples'];
    }

    public function display_apples() {
        echo $this->a;
    }
}