Include Extern Variable inside Method PHP - 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;
}
}

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();
}
}

Class static variables reset when I call them in other file

I am practicing PHP, and the issue I encountered today is my static variable getting reset every time I call it.
Login Page after verfied user from DB
<?php
Session::onlogin(1);
?>
This is my session class it has a func onlogin and I send some data to it from another file which change $is_signed to true. But the issue is variable $is_signed getting reset when I call it from index.php it returns false
<?php
class Session {
private static $is_signed = false;
function __construct(){
session_start();
}
public static function is_signed_in(){
return self::$is_signed;
}
public static function onLogin($userid){
if($userid){
session_regenerate_id();
$_SESSION['user_id'] = $userid;
self::$is_signed = true;
return true;
}
}
}
$session = new Session;
?>
Now I am calling it in index.php as below
if(Session::is_signed_in()){
echo "logged In";
}
else {
echo "error";
?>
I don't know where I am creating any error but when I call the methods.
So i asume this
class.php
class Session
{
private static $is_signed = false;
function __construct()
{
session_start();
}
public static function is_signed_in()
{
return self::$is_signed;
}
public static function onLogin($userid)
{
if ($userid) {
session_regenerate_id();
$_SESSION['user_id'] = $userid;
self::$is_signed = true;
return true;
}
}
}
$session = new Session;
login.php
<?php
require 'class.php';
$session = new Session;
Session::onlogin(1);
var_dump(Session::is_signed_in());// output true
index.php
<?php declare(strict_types = 1);
require 'class.php';
var_dump(Session::is_signed_in());// output false
think about it that login.php and index.php are 2 separate programs not aware one of each other.Thats why you try put SESSION there change
function __construct()
{
session_start();
if (isset($_SESSION['user_id'])){
self::$is_signed = true;
}
}
and you are done

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)

How To Get Variable From Constructor So It Can Be Used In Other Functions?

I have this code :
<?php
class Email{
public $mandrill_host;
public function __construct() {
$this->config_ini = parse_ini_file($_SERVER['DOCUMENT_ROOT'] . '/config.ini', true);
$this->mandrill_host = $config_ini['mandrill']['host'];
}
public function sendEmail () {
$res = $this->mandrill_host;
return $res;
}
}
$test = new Email;
echo $test->sendEmail ();
?>
and it gives me an empty result. it seems that the constructor method doesn't give the variable needed in sendEmail function. even though I already declared as public variable in class level.
how to get $this->mandrill_host from constructor so I can use it in any other method? what did I miss here?
Try
class Email{
public $mandrill_host;
public $config_ini; //you are missing this
public function __construct() {
$this->config_ini = parse_ini_file($_SERVER['DOCUMENT_ROOT'] . '/config.ini', true);
$this->mandrill_host = $this->config_ini['mandrill']['host'];
}
public function sendEmail () {
$res = $this->mandrill_host;
return $res;
}
}
$test = new Email;
echo $test->sendEmail ();
?>

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

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...

Categories