Set static variable from config's file in PHP - php

I have a simple PHP-static-class that writes in log.txt the log of my script.
It is:
<?php
class Log {
$fileLogConfig = ''; //include 'config.inc'; -> it's an error!
//Write the log in log.txt
public static function tracciaOperazioniNelLog($operation) {
$fileLog = fopen($fileLogConfig['log'], "a+") or die("Error! \n");
fwrite($fileLog, $operation . "\n");
fclose($fileLog);
}
}
?>
The $fileLogConfig is a variable that receives "log"'s param from config.inc.
This is my file config.inc:
<?php
return array(
...,
'log' => 'log.txt',
...
);
?>
But PHP says error about include 'config.inc'? Where is my error(s)?
Thanks!

You need to include the file in a constructor.
<?php
class Log {
public $fileLogConfig;
function __construct(){
$this->fileLogConfig = include 'config.inc.php';
}
}
$o = new Log();
print_r($o->fileLogConfig);
UPDATE
I overlooked that OP has a static class.
So, create an initialize() method to set your static variables.
class Log {
public static $fileLogConfig;
public static function initialize(){
self::$fileLogConfig = include 'config.inc.php';
}
}
Log::initialize();
print_r(Log::$fileLogConfig);

Related

How to persist data in a PHP application

Why might a static variable I've initialized in a class become unset? Here is class( is 'static' ):
class Events {
// static events collection
private static $events = null;
// private(unused) constructor
private function __construct() {}
// initializes the class
public static function initialize($events){
self::$events = $events;
}
// returns the event collection
public static function get(){
return self::$events;
}
}
I set $events like this:
functions.php:
include_once "events.php";
// a function to initialize the application
function init(){
// retrieve events from database
$events = get_events_from_server();
// initialize the events class
Events::initialize($events);
}
init() is called from index.php.
The variable seems to be unset after index.php has completely loaded. I post from javascript to a server page: get_events.php to request the list of json encoded events. At get_events.php the static events variable is null. Here is get_events.php:
<?php
include_once "../ccc-psl-config.php";
include_once WEBROOT ."/includes/functions.php";
include_once WEBROOT ."/includes/db_connect.php";
include_once WEBROOT ."/types/events.php";
ob_start();
try{
// open database connection
$pdo = DatabaseConnection::open();
$events = Events::get();
//$events = get_events($pdo);
if($events){
echo $events;
}
else {
echo false;
}
}
catch(Exception $e){
print_r("Failed to get events from database: ".$e.getMessage());
echo false;
}
// close database connection
DatabaseConnection::close();
ob_end_flush();

PHP extends namespace\class unknown error

This is my parent class code: \core\controller\controlmaster
<?php
namespace core\controller;
class controlmaster{
private $model_base = null;
//public function __construct(){
//always start session for any loaded controller
//session_start();
//}
public function _loadModels($models){
$file = dirname(dirname(__DIR__)).DIRECTORY_SEPARATOR.$this->model_base.$models.".php";
$file_alloc = str_replace("\\","/",$file);
if(file_exists($file_alloc)){
require($file_alloc);
$models_name = $this->model_base.$models;
return new $models_name();
}
}
public static function _setModelBase($model_location){
$this->model_base = $model_location;
}
}
?>
and this is my controller page for application : \applications\controller\index
<?php
namespace applications\controllers;
use core\configuration\configloader as config;
class index extends \core\controller\controlmaster{
public $config;
public function __construct(){
$this->config = new config;
$this->config->_parsePHP("j3mp_setting.php");
parent::_setModelBase($this->config->settings['app_model_base']); // Error doesn't appear when i comment this function
echo "This is main page and this is config for model app base : {$this->config->settings['base_url']}";
}
}
?>
This is core\configuration\configloader:
<?php
namespace core\configuration;
class configloader{
//Contains setting informations
public $inisettings;
public $settings;
public function _parseINI($file,$section){
$section = empty($section) ? false : true;
$file = __DIR__.DIRECTORY_SEPARATOR.$file;
if(file_exists($file)){
$parse = parse_ini_file($file,$section);
$this->inisettings = $parse;
}else{
throw new core\errorhandler\exception("File {$file} is not found in our system. Please contact administrator for details.","configloader");
}
}
public function _parsePHP($file){
$file = __DIR__.DIRECTORY_SEPARATOR.$file;
if(file_exists($file)){
$settings = array();
include($file);
$this->settings = $settings;
}else{
throw new core\errorhandler\exception("File {$file} is not found in our system. Please contact administrator for details.","configloader");
}
}
}
?>
When i comment "parent::_setModelBase(...)" code, the error disappear and the browser successfully print "This is main page and this is config for model app base : http://iosv3.net/". I think the error come from \core\controller\controlmaster, but I don't know how to fix that? I always try to edit the file (\core\controller\controlmaster) but notting happens... If error occured, the message ("This is main page ...") doesn't come out... Could you show me where is the error come from? Thanks...

Include Extern Variable inside Method PHP

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?
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;
}
}
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;
}
}

using php include function for classes

Trying to get a hang of classes in php, trying to include carClass.php into new_file.php.
carClass.php
<?php
class carClass
{
private $color;
private $gear;
private $model;
private $gas;
function paintCar($carColor) {
$this->color = $carColor;
}
function findCarColor() {
echo "$color";
}
function shiftGear($newGear) {
$this->gear=$newGear;
}
function findGear() {
echo "$gear";
}
function chooseModel($newModel) {
$this->model = $newModel;
}
function findModel() {
echo"$model";
}
function fillCar($gasAmount) {
$this->gas = $gasAmount;
}
function lookAtGauge() {
echo "$gas";
}
}
?>
its just a bunch of getters and setters. Im trying to include this class to new_file.php
new_file.php
<?php
include("carClass.php");
$car = new carClass;
$car->chooseModel("Mustang");
$car->paintCar("black");
$car->shiftGear("5th");
$car->fillCar("half");
$car->findModel();
$car->findCarColor();
$car->findGear();
$car->lookAtGuage();
?>
When I try to execute this file I get these error messages
Warning: include(carClass.php): failed to open stream: No such file or directory in C:\xampp\htdocs\testFile\new_file.php on line 4
Warning: include(): Failed opening 'carClass.php' for inclusion (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\testFile\new_file.php on line 4
Fatal error: Class 'carClass' not found in C:\xampp\htdocs\testFile\new_file.php on line 6
I believe both files are in testFile directory so I'm not sure whats going on. I appreciate any help you guys can give me as usual.
The include path is set against the server configuration (PHP.ini) but the include path you specify is relative to that path so in your case the include path is (actual path in windows):
<?php
include_once dirname(__FILE__) . '/carClass.php';
$car = new carClass;
$car->chooseModel("Mustang");
$car->paintCar("black");
$car->shiftGear("5th");
$car->fillCar("half");
$car->findModel();
$car->findCarColor();
$car->findGear();
$car->lookAtGuage();
?>
You can use PHP's auto loading feature which will automatically load a class when an object is created. If you have many classes then you can use it an header file so that you don't need to worry about using this include every time.
<?php
function __autoload($class_name) {
include $class_name . '.php';
}
$obj = new MyClass1();
$obj2 = new MyClass2();
?>
Try this:
<?php
class carClass
{
private $color;
private $gear;
private $model;
private $gas;
function paintCar($carColor) {
$this->color = $carColor;
}
function findCarColor() {
echo $this->color;
}
function shiftGear($newGear) {
$this->gear=$newGear;
}
function findGear() {
echo $this->gear;
}
function chooseModel($newModel) {
$this->model = $newModel;
}
function findModel() {
echo $this->model;
}
function fillCar($gasAmount) {
$this->gas = $gasAmount;
}
function lookAtGauge() {
echo $this->gas;
}
}
?>
//
<?php
include("carClass.php");
$car = new carClass;
$car->chooseModel("Mustang");
$car->paintCar("black");
$car->shiftGear("5th");
$car->fillCar("half");
$car->findModel();
$car->findCarColor();
$car->findGear();
$car->lookAtGauge();
?>

including class within another class in php

i have a php page which has some variables regarding database i.e server address, username and password etc.
config.php will include
<?php
$dbserver="";
$username="";
$password="";
$database="";
?>
i have a class which contains all the functions required for my website. How can i import my php page variables into this class to be used for the database connectivity?
my class
<?php
class a{
include("config.php");
function db_connect(){
mysql_connect($dbserver,$username,$password);
}
}
?>
usually for this purpose, Constants exist.
But if you want to use variables, all you have to do is to require_once(yourFile), then when you want to use these variables (which are global) inside a method of a class, simply refer to them as global $myVar; (as if you're declaring it). Only need to do this once for each global variable you want to use in the context.
Example:
settings.php:
$conn = 'my connection';
MyClass.php:
class MyClass
{
function DoSomething()
{
require_once('settings.php');
global $conn;
doSomethingWith($conn);
}
}
Update
For a Database class that requires configuration options, the simplest way would be to use the config values as parameters (example 1 of my original answer below).
A more complex, though also more flexible approach would be a Config-Class.
class Config
{
private $config = array();
public function __construct(array $config)
{
$this->config = $config;
}
public function Register($key, $value)
{
$this->config[$key] = $value;
}
public function Get($key)
{
if (!isset($this->config[$key])) return null;
return $this->config[$key];
}
}
Your DB class would look something like this:
class Database
{
private $config = null;
public function __construct(Config $config)
{
$this->config = $config;
}
public function Connect()
{
do_connect_stuff($this->config->Get('host'), $this->config->Get('user'), .....);
}
}
File config.php
<?php
$config = new Config(
array(
"host" => "localhost",
"user" => "user",
...
)
);
/*
alternative:
$config = new Config();
$config->Register('host', 'localhost');
$config->Register('user', 'user');
...
*/
?>
File that requires the database:
<?php
$database = new Database($config);
$database->Connect();
?>
As a side hint: Use PDO, it's far better than the old mysql_* functions.
Original Answer
The proper style would be to pass the variables to the functions as parameter or pass them when creating the object. You can also use Init methods to pass the parameters.
Examples:
(Which of the following code you should use depends on what you already have and how your code is designed, the 'cleanest' way would be an object for which you transmit the variables when calling the ProcessAction method)
Assuming that in your script you have a Variable $action which you get from $_GET or some other way.
Using an Object
class Controller
{
public function ProcessAction($action, $some_other_parameter, $and_yet_another_parameter)
{
[...]
}
}
You then call it with
$action = do_some_stuff_to_get_action();
$controller = new Controller();
$controller->ProcessAction($action, $other_parameter, $second_parameter);
Using a static class
class Controller
{
public static function ProcessAction($action, $some_other_parameter, $and_yet_another_parameter)
{
[...]
}
}
Called with:
$action = do_some_stuff_to_get_action();
Controller::ProcessAction($action, $other_parameter, $second_parameter);
Passing the parameters before calling the function
Object
class Controller
{
private $action = "";
private $some_other_parameter = "";
public function __construct($action, $some_other_parameter)
{
$this->action = $action;
$this->some_other_parameter = $some_other_parameter;
}
public function ProcessAction()
{
if ($this->action == 'do_stuff')
{
[...]
}
}
}
Called with:
$action = do_some_stuff_to_get_action();
$controller = new Controller($action, $other_parameter);
$controller->ProcessAction();
Static methods
class Controller
{
private static $action = "";
private static $some_other_parameter = "";
public static function Init($action, $some_other_parameter)
{
self::$action = $action;
self::$some_other_parameter = $some_other_parameter;
}
public static function ProcessAction()
{
if (self::$action == 'do_stuff')
{
[...]
}
}
}
Called with:
$action = do_some_stuff_to_get_action();
Controller::Init($action, $other_parameter);
Controller::ProcessAction();
I used the database configuration in the constructor of the class. I think that was the only solution not including any third page in the scenario.

Categories