Hello I'm trying to make a simple configuration file for my app my project folder is: inside folder 'app' -Config.php inside root directory: -index.php -config.php
this is how config.php looks like:
<?php
return [
'db' => [
'hosts' => [
'local' => 'localhost',
'externo' => '1.1.1.1',
],
'name' => 'db-stats',
'user' => 'root',
'password' => 'root'
],
'mail' => [
'host' => 'smtp.gmail.com'
]
];
?>
Config.php is:
<?php
namespace Project\Helpers;
class Config
{
protected $data;
protected $default = null;
public function load($file){
$this->$data = require $file;
}
public function get($key, $default = null){
$this->$default = $default;
$segments = explode('.', $key);
$data = $this->$data;
foreach ($segments as $segment) {
if(isset($data[$segment])){
$data = $data[$segment];
}else{
$data = $this->$default;
break;
}
}
return $data;
}
public function exists($key){
return $this->get($key) !== $this->$default;
}
}
?>
and finally index.php:
<?php
use Project\Helpers\Config;
require 'app/Config.php';
$config = new Config;
$config->load('config.php');
echo $config->get('db.hosts.local');
?>
the thing is I'm getting this 2 errors when I run the page:
Notice: Undefined variable: data in C:\\xampp\\htdocs\\probar\\app\\Config.php on line 11
Fatal error: Cannot access empty property in C:\\xampp\\htdocs\\probar\\app\\Config.php on line 11
please help me what's is wrong with this???
$this->data = require $file;
not
$this->$data = require $file;
.
And $this->default = $default;
instead of
$this->$default = $default;
Otherwise those would be variable variables .
<?php
namespace Project\Helpers;
class Config
{
protected $data;
protected $default = null;
public function load($file){
$this->data = require $file;
}
public function get($key, $default = null){
$this->default = $default;
$segments = explode('.', $key);
$data = $this->data;
foreach ($segments as $segment) {
if(isset($data[$segment])){
$data = $data[$segment];
}else{
$data = $this->default;
break;
}
}
return $data;
}
public function exists($key){
return $this->get($key) !== $this->default;
}
}
You have a synthax error in the class constructor. In PHP, when you access a member attribute with the ->
operator, you don't have to use the $
modifier.
The correct code looks like this:
<?php
namespace Project\Helpers;
class Config
{
protected $data;
protected $default = null;
public function load($file){
$this->data = require $file;
}
public function get($key, $default = null){
$this->default = $default;
$segments = explode('.', $key);
$data = $this->data;
foreach ($segments as $segment) {
if(isset($data[$segment])){
$data = $data[$segment];
}else{
$data = $this->default;
break;
}
}
return $data;
}
public function exists($key){
return $this->get($key) !== $this->default;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.