Search code examples
phpclassrequire-once

Require_once external vars and share those with other funcions in a php class


I have an external file with some vars to require in my php class and share those with all functions of my class:

vars.inc:

<?php
 $a = 1;
?>

class.php:

<?php
 class A{
  public function __construct(){
   require_once("vars.inc");
  }
  public function aB{
   echo $a;
  }
 }
?>

but it doesn't work: the $a var is undefined

how can I do?

thanks all


Solution

  • The variables in a function only exist in local scope, unless you assign them to class variables.

    For example, if you had this in your included page:

    <?php
    $myvariable = 'hello';
    ?>
    

    Then your class should use the $this to assign it to a class variable.

    myvariable = $myvariable; } public function aB{ echo $myvariable; } } ?>

    See the manual for more information about variable scope.