title: How do I set a PHP variable from within a PHP class
body: <p>Here is what I'm trying to do:</p>
  <ol>
  <li>Connect to a MySQL database using a class (Sorted)</li>
  <li>Query a MySQL table (Sorted)</li>
  <li>Set a PHP global PHP variable that can be referenced throughout the website (Not Sorted)</li>
  </ol>
  <p><em><strong>Database connection class</strong></em></p>
  <pre><code>&lt;?php
  
  class dbh
  {
  
      private $servername;
      private $username;
      private $password;
      private $dbname;
  
      protected function connect()
      {
  
          $this-&gt;servername =&quot;localhost&quot;;
          $this-&gt;username =&quot;neo&quot;;
          $this-&gt;password =&quot;p.MR~11^&quot;;
          $this-&gt;dbname =&quot;neo_db&quot;;
  
          $conn = new mysqli($this-&gt;servername, $this-&gt;username, $this-&gt;password, $this-&gt;dbname);
  
          return $conn;
  
      }
  
  }
  
  ?&gt;
  </code></pre>
  <p>This is my dbh.inc.php file and it works fine and produces zero errors.</p>
  <p><em><strong>SQL SELECT class</strong></em></p>
  <pre><code>&lt;?php
  
  class modules extends dbh
  {
  
      protected function getallmodules()
      {
  
          $sql = &quot;SELECT * FROM modules&quot;;
          $result = $this-&gt;connect()-&gt;query($sql);
          $numRows = $result-&gt;num_rows;
  
          if($numRows &gt; 0)
          {
  
              while($row = $result-&gt;fetch_assoc())
              {
  
                  $data[] = $row;
  
              }
  
              return $data;
  
          }
  
      }
  
  }
  
  ?&gt;
  </code></pre>
  <p>This is my modules.inc.php file and it works fine and produces zero errors.</p>
  <p><em><strong>SQL view modules class</strong></em></p>
  <pre><code>&lt;?php
  
  class viewmodules extends modules
  {
  
      public $widgets;
  
      public function showallmodules()
      {
  
          $modules = $this-&gt;getallmodules();
          
          foreach($modules as $module)
          {
  
              $this-&gt;module['widgets'];
  
          }
  
      }
  
  }
  
  ?&gt;
  </code></pre>
  <p>This is my viewmodules.inc.php file. I need to set a global variable called $widgets.</p>
  <p><em><strong>PHP output page</strong></em></p>
  <pre><code>&lt;?php
  
      $modules = new viewmodules();
      $modules-&gt;showallmodules();
  
      if($modules-&gt;widgets):
  
      //some code here
  
      endif;
  
  ?&gt;
  </code></pre>