title: How should I share / pass variables across different methods in a PHP Class?
body: <p>I am trying to set a value from a method of a class and trying to get it in another method. The example code is as below. I think the below kind of set/get works in a Java class. Googled out but still could not find a relevant solution. </p>
  
  <p>I searched for "how to share data across functions in PHP" and found <a href="https://stackoverflow.com/questions/1750837/php-call-member-variables-off-a-class-within-static-method">How can I call member variables of a class within a static method?</a>, but that did not answer my question.</p>
  
  <pre><code>&lt;?php
  class MyClass
  {
      public $cons;
  
      function showConstant() {
          $this-&gt;setConstant(100); /* assign value to variable here */
          $this-&gt;showConstantGetter();
      }
  
      /* setter */
      function setConstant($aCons) {
          $cons  = $aCons;
      }
  
      /* getter */
      function getConstant() {
          return $cons;
      }
  
  
      function showConstantGetter() {
          echo "&lt;br&gt;getting const : ".$this-&gt;getConstant(); /* use the variable's value in this method here */
      }
  
  }
  
  $classname = "MyClass";
  $class = new MyClass();
  $class-&gt;showConstant();
  
  ?&gt;
  </code></pre>