how to use global variables in php class in a MVC project - php

I want to $st_id in a function in my model class in a mvc project, as you see below, but it get me an error that $st_id is not defined. what I can do for resolve this problem ?
<?php
#session_start();
$st_id=$_SESSION['username'];
if (!isset($_SESSION['USERNAME']))
{
header('Location: signin.php');
}
//////////////////////
class model
{
private $result;
public $rp_result;
//////////
public function exe_query()
{
$mysqldb = new MySQLDatabase();
$result=$mysqldb->query('CALL view_report('.$this->st_id.');');
$this->rp_result=$mysqldb->fetch_all($result);
}
}
?>

How do you call your model ?
I suggest you:
class model
{
private $result;
public $rp_result, $st_id;
public function __construct($st_id)
{
$this->st_id = $st_id;
}
public function exe_query()
{
$mysqldb = new MySQLDatabase();
$result=$mysqldb->query('CALL view_report('.$this->st_id.');');
$this->rp_result=$mysqldb->fetch_all($result);
}
}
And now, you can use:
#session_start();
$st_id=$_SESSION['username'];
if (!isset($_SESSION['USERNAME']))
{
header('Location: signin.php');
}
$model = new model($st_id);
$model->exe_query();

You have to declare it within the class if you're using it with $this
class model {
public $st_id;
public function __construct() {
#session_start();
$this->st_id = $_SESSION['username'];
}
public function exe_query()
{
$mysqldb = new MySQLDatabase();
$result=$mysqldb->query('CALL view_report('.$this->st_id.');');
$this->rp_result=$mysqldb->fetch_all($result);
}
}

Why not call it directly as $_SESSION['username']? It's already global...

Related

Require has failed in php

I'm new to PHP, I'm trying to require UserController.php from Controller.php but all I get is "HTTP ERROR 500" in browser. What's going on here?
Controller.php
class Controller
{
public function __construct()
{
}
public function call(){
// echo 1;
require_once "../Controllers/UserController.php";
}
}
UserController.php
class UserController
{
public function __construct()
{
echo '111111111';
}
public function hi(){
echo '1';
}
}
$a = new UserController();
$a->hi();
Class definitions can't be nested inside functions or other classes. So you shouldn't have that require_once line inside a function definition. Move it outside the class.
require_once "../Controllers/UserController.php";
class Controller
{
public function __construct()
{
}
public function call(){
// echo 1;
}
}
<?php
require_once "../Controllers/UserController.php";
class Controller
{
public function __construct()
{
}
public function call(){
// echo 1;
$a = new UserController();
$a->hi();
}
}

How to access global variable from inside class's function

I have file init.php:
<?php
require_once 'config.php';
init::load();
?>
with config.php:
<?php
$config = array('db'=>'abc','host'=>'xxx.xxx.xxx.xxxx',);
?>
A class with name something.php:
<?php
class something{
public function __contruct(){}
public function doIt(){
global $config;
var_dump($config); // NULL
}
}
?>
Why is it null?
In php.net, they told me that I can access but in reality is not .
I tried but have no idea.
I am using php 5.5.9.
The variable $config in config.php is not global.
To make it a global variable, which i do NOT suggest you have to write the magic word global in front of it.
I would suggest you to read superglobal variables.
And a little bit of variable scopes.
What I would suggest is to make a class which handles you this.
That should look something like
class Config
{
static $config = array ('something' => 1);
static function get($name, $default = null)
{
if (isset (self::$config[$name])) {
return self::$config[$name];
} else {
return $default;
}
}
}
Config::get('something'); // returns 1;
Use Singleton Pattern like this
<?php
class Configs {
protected static $_instance;
private $configs =[];
private function __construct() {
}
public static function getInstance() {
if (self::$_instance === null) {
self::$_instance = new self;
}
return self::$_instance;
}
private function __clone() {
}
private function __wakeup() {
}
public function setConfigs($configs){
$this->configs = $configs;
}
public function getConfigs(){
return $this->configs;
}
}
Configs::getInstance()->setConfigs(['db'=>'abc','host'=>'xxx.xxx.xxx.xxxx']);
class Something{
public function __contruct(){}
public function doIt(){
return Configs::getInstance()->getConfigs();
}
}
var_dump((new Something)->doIt());
Include the file like this:
include("config.php");
class something{ ..
and print the array as var_dump($config); no need of global.
Change your class a bit to pass a variable on the constructor.
<?php
class something{
private $config;
public function __contruct($config){
$this->config = $config;
}
public function doIt(){
var_dump($this->config); // NULL
}
}
?>
Then, if you
include config.php
include yourClassFile.php
and do,
<?php
$my_class = new something($config);
$my_class->doIt();
?>
It should work.
Note: It is always good not to use Globals (in a place where we could avoid them)

Why not global $db in model classes?

Let's say that we have a MVC pattern. If we have something like this:
blog_controller.php
<?php
class c_blog{
private $model;
public function __construct(){
include( [model_path] );
$this->model = new m_blog();
}
public function post_list(){
return $this->model->get_list();
}
}
blog_model.php
<?php
class m_blog{
public function get_list(){
global $db;
$sel = $db->query("...");
$sel = $db->fetch_array($sel);
return $sel;
}
}
index.php
<?php
$db = new database();
include "blog_controller.php";
$blog = new c_blog();
var_dump( $blog->post_list() );
?>
Why the above example isn't good, and a lot of devs want OOP like class m_blog extends database{} ?
I want only the advantages and disavantages, because I use this "worry" method on over 15 sites with a high traffic and I don't have problems (some of that websites work with multidatabases and it's very easy to change global $db, to global $db_five.)
Thanks!
Why not use inheritance?
<?php
class model {
private $db;
public function __construct() {
$this->initDb();
}
private function initDb();
}
class c_blog {
private $model;
public function __construct(){
include( [model_path] );
$this->model = new m_blog();
}
public function post_list(){
return $this->model->get_list();
}
}
class m_blog extends model{
public function __construct() {
parent::__construct;
}
public function get_list(){
$sel = $this->db->query("...");
$sel = $this->db->fetch_array($sel);
return $sel;
}
}

How to access a variable with random value inside a class?

class Session{
protected $git = md5(rand(1,6));
public function __construct($config = array())
{
//// some code
$ses_id = $this->git;
}
public function _start_session()
{
//code again..
}
}
Here I can't assign a random value like this to variable called git. How can I do this if it is possible?
That random value need to be first time generated value only till the time it converts to Null.
Perform random inside your constructor,
class Session{
protected $git;
public function __construct($config = array())
{
//// some code
$this->git = md5(rand(1,6));
$ses_id = $this->git;
}
public function _start_session()
{
//code again..
}
}
Try setting the value of your variable in your constructor.
constructor will run every time you create an instance of your class.
try this code:
class Session{
protected $git;
public function __construct($config = array())
{
//// some code
$this->git = md5(rand(1,6));
}
public function _start_session()
{
//code again..
}
}
:)
Declare a variable inside a class,initialize the variables in class inside a constructor, which sets the variables once the object for that class is declared anywhere in the code.
I updated this answer if you want to do not change your session variable on each constructor call then use the below procedure.
class Session{
protected $git;
public function __construct($config = array())
{
$this->git = md5(rand(1,6));
if(!isset($_SESSION['ses_id']))
{
$_SESSION['ses_id'] = $this->git;
}
}
public function _start_session()
{
//code again..
}
}
I hope this helps you.
Try this using a global variable to track the random number:
class Session{
protected $git;
public function __construct($config = array())
{
//// some code
if (!isset($GLOBALS['random_val'])) {
$GLOBALS['random_val'] = md5(rand(1,6));
}
$this->git = $GLOBALS['random_val'];
$ses_id = $this->git;
var_dump("Session ID: ".$ses_id);
}
public function _start_session()
{
//code again..
}
}
$ses1 = new Session(); // Outputs string(44) "Session ID: 1679091c5a880faf6fb5e6087eb1b2dc"
$ses2 = new Session(); // Outputs string(44) "Session ID: 1679091c5a880faf6fb5e6087eb1b2dc"

Code is not getting executed when I include this class PHP

I took good care to create this class but I am not sure what is wrong with it. The code runs perfectly if I don't have any content inside,
class TemplateOne{
}
But once I run this code it breaks,
<?php
class TemplateOne {
//Properties
protected $_bgColor;
protected $_logoImagePath;
protected $_headerText;
protected $_leftContentHeader;
protected $_rightContentHeader;
protected $_leftContentBody;
protected $_rightContentBody;
protected $_footer;
protected $_mediaIframe;
protected $_mediaHeight = '';
protected $_mediaWidth = '';
//DB communication
public $DB;
//Constructor
public function __construct(){
//Connect database in construct and close connection in destruct
$config = array();
$config['host'] = 'localhost';
$config['user'] = 'root';
$config['pass'] = 'root';
$config['database'] = 'fanpage_application';
$this->DB = new DB($config);
//init variables
populateDataFromDataBase();
}
//Functions
public function populateDataFromDataBase() {
//Get bgcolor
$this->DB->("SELECT backgroundimage FROM template_style_data WHERE styleid='#list_level'");
$data = $this->DB->Get();
foreach($data as $key => $value)
{
echo $value['backgroundimage'];
}
}
//Getters
public function getBgColor()
{
return $this->_bgColor;
}
public function getLogoImagePath()
{
return $this->_logoImagePath;
}
public function getHeaderText()
{
return $this->_headerText;
}
public function getLeftContentHeader()
{
return $this->_leftContentHeader;
}
public function getRightContentHeader()
{
return $this->_rightContentHeader;
}
public function getLeftContentBody()
{
return $this->_leftContentBody;
}
public function getRightContentBody()
{
return $this->_rightContentBody;
}
public function getFooter()
{
return $this->_footer;
}
public function getMediaIframe()
{
return $this->_mediaIframe;
}
//Setters
public function setBgColor($bgColor)
{
$this->_bgColor = $bgColor;
}
public function setLogoImagePath($logoImagePath)
{
$this->_logoImagePath = $logoImagePath;
}
public function setHeaderText($headerText)
{
$this->_headerText = $headerText;
}
public function setLeftContentHeader($leftContentHeader)
{
$this->_leftContentHeader = $leftContentHeader;
}
public function setRightContentHeader($rightContentHeader)
{
$this->_rightContentHeader = $rightContentHeader;
}
public function setLeftContentBody($leftContentHeader)
{
$this->_leftContentBody = $leftContentHeader;
}
public function setRightContentBody($rightContentBody)
{
$this->_rightContentBody = $rightContentBody;
}
public function setFooter($footer)
{
$this->_footer = $footer;
}
public function setMediaIframe($mediaIframe)
{
$this->_mediaIframe = $mediaIframe;
}
}
?>
You are missing $this-> from your call to populateDataFromDataBase.
Where is the DB class coming from? You may have to include the correct class definition file if it is not already.
$this->DB = new DB($config);
The following is not legal syntax. You will need to actually call a function by name.
$this->DB->("SELECT backgroundimage FROM template_style_data WHERE styleid='#list_level'");
Unless you have another function in the global scope named populateDataFromDataBase which is what you want to call, you will need to add $this-> before you try to call it in your constructor.
populateDataFromDataBase();
Here is your error:
$this->DB->("SELECT backgroundimage FROM template_style_data WHERE styleid='#list_level'");
This is not valid syntax, you need to call a method after $this->DB.
As far as I'm concerned there is only one possible answer: check your PHP errors http://php.net/manual/en/function.error-reporting.php
at least (in devevlopment only, don't show errors in production):
ini_set('display_errors', 1);
error_reporting(-1);

Categories