1

I have this code:

//config.php
$EXAMPLE['try1'] = "...." ;
$EXAMPLE['try2'] = "...." ;

So, i have another file with a php class:

class try {
   public function __construct() {
       if($this->try1() && $this->try2()){
            return true;
       }
   }
   public function try1(){
   require_once 'config.php' ;
   echo $EXAMPLE['try1'];
   return true;
   }
   public function try2(){
   require_once 'config.php' ;
   echo $EXAMPLE['try2'];
   return true;
   }
}

But in my case, $EXAMPLE['try1'] is ..... , but $EXAMPLE['try2'] is null... why? I've tried to include require_once 'config.php' ; on top page, and add after global $EXAMPLE; , but $EXAMPLE is ever null, why?

tereško
  • 58,060
  • 25
  • 98
  • 150
Carbos
  • 117
  • 8

2 Answers2

2

Use require, not require_once. Otherwise, if you load the file in one function, it won't be loaded in the other function, so it won't get the variables.

It would be better to require the function outside the functions entirely. Then declare $EXAMPLE as a global variable.

require_once 'config.php';

class try {
    public function __construct() {
        if($this->try1() && $this->try2()){
            return true;
        }
    }
    public function try1(){
        global $EXAMPLE
        echo $EXAMPLE['try1'];
        return true;
    }
    public function try2(){
        global $EXAMPLE
        echo $EXAMPLE['try2'];
        return true;
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Require your file inside __construct method. So require once requires file once in try1 method.

class try {

    private $_example = array();

    public function __construct() {

        require_once 'config.php';

        $this->_example = $EXAMPLE;

        return $this->try1() && $this->try2();
    }

     public function try1(){
        echo $this->_example['try1'];
        return true;
     }

     public function try2(){
        echo $this->_example['try2'];
        return true;
     }
}
doubleui
  • 516
  • 2
  • 8