views:

25

answers:

3

Hi all, 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

+1  A: 
Lotus Notes
thanks, it works, however we have to retrieve var trough $this->var. Hi!
frx08
A: 

It's a scope issue. Maybe this will be better:

<?php
 class A{
  protect $a;
  public function __construct(){
   require_once("vars.inc");
   $this->a = $a;

  }
  public function aB{
   echo $this->a;
  }
 }
?>
John Conde
-1. Not only does this not work ($a disappears after __construct() occurs), but it encourages poor use of globals. The included page inherits the scope of where it's included, unless you define functions in the included page in which case the functions are global. Also, no need to downrate my comment.
Lotus Notes
You were quick to downvote. If you would have waited you would have seen me expand my answer and provide a better alternative.
John Conde
@John But your initial code is wrong. When you require in the __construct it becomes a local variable of the construct. For your first code to work the vars.inc file would have to be required outside of the class
AntonioCS
A: 

That is generally a bad practice. Either give the variables to the class through the constructor or the methods, or create a Static class that holds the variables or globally accessible variable that will hold those values. It depends on your code and exactly you are trying to do.

Ivo Sabev