Global variable without having to redeclare every function? - php

I want to have access to a global variable without having to redeclare every function. Here is an example.
$mobile = 1;
class Database
{
private $connect;
function one($argumentarray)
{
global $mobile;
echo $mobile;
}
function two($argumentarray)
{
global $mobile;
echo $mobile;
}
function three($argumentarray)
{
global $mobile;
echo $mobile;
}
}
I have about 100 functions and i need access to the $mobile variable in all of them. Is there a way to do this without having to do global $mobile in every function?

The best way would be to NOT use the global. Design your program in a way that it can live without globals. That's it.
A simple design that comes in mind, might look like:
class Configuration {
protected static $mobile = 1;
// let's say it's write protected -> only a getter.
public static mobile() {
return self::$mobile;
}
}
class Database {
// use the config value
function one() {
if(Configuration::mobile()) {
...
}
}
}

Use the $GLOBALS array.
$GLOBALS["mobile"]
Or you could store the variable in your class - which is cleaner in my opinion.

Well, You could do something like this:
class Database
{
private $connect;
private $mobile;
function __construct() {
#assign a value to $mobile;
$this->mobile = "value";
}
function one($argumentarray)
{
echo $this->mobile;
}
function two($argumentarray)
{
echo $this->mobile;
}
function three($argumentarray)
{
echo $this->mobile;
}
}

Already 5 answers and nobody mentioned static class variables yet.
Copying the variable in the constructor would be wasteful, impractical and hurt readability. What if you need to change the value of this global later on? Every object will be stuck with an obsolete copied value. This is silly.
Since you need a prefix to access this "global" anyway, let it be self:: or Database:: rather than this-> :).
It will
allow you to set the variable directly from the class definition,
not waste memory doing a copy of it for each object
make it accessable from outside if you whish so (if you declare it public)
In your example:
class Database {
static private $mobile = "whatever";
function one($argumentarray)
{
echo self::$mobile;
}
function two($argumentarray)
{
echo self::$mobile;
}
function three($argumentarray)
{
echo self::$mobile;
}
}
If you want to allow modifications from outside :
static private $mobile;
static function set_mobile ($val) { self::$mobile = $val; }
static function get_mobile ($val) { return self::$mobile; }
or
static public $mobile;

Maybe a class attribute, and set it with the constructor?
class myClass {
private $mobile;
/* ... */
}
In the constructor, do:
public function __construct() {
$this->mobile = $GLOBALS['mobile'];
}
And then use:
$this->mobile
from everywhere!

Pass the variable to the constructor, and set a class level variable.
It can then be accessed in the varius methods using $this->
$mobile = 1;
class Database
{
private $connect;
private $mobile
function __construct($mobile){
$this->mobile=$mobile;
}
function one($argumentarray)
{
echo $this->mobile;
}
function two($argumentarray)
{
echo $this->mobile;
}
function three($argumentarray)
{
echo $this->mobile;
}
}
$db = new Database($mobile);

Related

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

PHP how set default value to a variable in the class?

class A{
public $name;
public function __construct() {
$this->name = 'first';
}
public function test1(){
if(!empty($_POST["name"]))
{
$name = 'second';
}
echo $name;
}
$f = new A;
$f->test1();
Why don't we get first and how set right default value variable $name only for class A?
I would be grateful for any help.
You can use a constructor to set the initial values (or pretty much do anything for that matter) as you need to like this:
class example
{
public $name;
public function __construct()
{
$this->name="first";
}
}
Then you can use these default values in your other functions.
class example
{
public $name;
public function __construct()
{
$this->name="first";
}
public function test1($inputName)
{
if(!empty($inputName))
{
$this->name=$inputName;
}
echo "The name is ".$this->name."\r\n";
}
}
$ex=new example();
$ex->test1(" "); // prints first.
$ex->test1("Bobby"); // prints Bobby
$ex->test1($_POST["name"]); // works as you expected it to.
you have two options to set the default values for the class attributes:
Option 1: set at the parameter level.
class A
{
public $name = "first";
public function test1()
{
echo $this->name;
}
}
$f = new A();
$f->test1();
Option 2: the magic method __construct() always being executed each time that you create a new instance.
class A
{
public $name;
public function __construct()
{
$this->name = 'first';
}
public function test1()
{
echo $this->name;
}
}
$f = new A();
$f->test1();
Use isset() to assign a default to a variable that may already have a value:
if (! isset($cars)) {
$cars = $default_cars;
}
Use the ternary (a ? b : c) operator to give a new variable a (possibly default) value:
$cars = isset($_GET['cars']) ? $_GET['cars'] : $default_cars;

Use a variable from __construct() in other methods

I defined a new variable in __construct() and I want to use it in another function of this class.
But my variable is empty in the other function!
this is my code:
class testObject{
function __construct() {
global $c;
$data = array("name"=>$c['name'],
"family"=>$c['family']);
}
function showInfo() {
global $data;
print_r($data);
}
}
Declare variable $data as global inside the constructor:
function __construct() {
global $c;
global $data;
$data = array("name"=>$c['name'],
"family"=>$c['family']);
}
Then, it will be visible in other function as well.
Note that extensive usage of global variables is strongly discouraged, consider redesigning your class to use class variables with getters+setters.
A more proper way would be to use
class testObject
{
private $data;
function __construct(array $c)
{
$this->data = array(
"name"=>$c['name'],
"family"=>$c['family']
);
}
function showInfo()
{
print_r($this->data);
}
// getter: if you need to access data from outside this class
function getData()
{
return $this->data;
}
}
Also, consider separating data fields into separate class variables, as follows. Then you have a typical, clean data class.
class testObject
{
private $name;
private $family;
function __construct($name, $family)
{
$this->name = $name;
$this->family = $family;
}
function showInfo()
{
print("name: " . $this->name . ", family: " . $this->family);
}
// getters
function getName()
{
return $this->name;
}
function getFamily()
{
return $this->family;
}
}
And you can even construct this object with data from you global variable $c until you elimitate it from your code:
new testObject($c['name'], $c['family'])
You can do this way. Instead of declaring $data as global variable declare as public or private or protected variable inside the class depending on your use. Then set the data inside _construct.
Using global inside a class is not a good method. You can use class properties.
class testObject{
public $data;
function __construct() {
global $c;
$this->data = array("name"=>$c['name'],
"family"=>$c['family']);
}
function showInfo() {
print_r($this->data);
}
}

Access a variable nested in a function inside a class in php

Here is a cut down version of my code with the main class and main function
I need to get the value of 'userName' that input by the user to use it inside 'mainFunction', tried making the 'userName' inside 'myForm' global but that didn't get the value out.
can value of 'userName' be available out side 'mainClass' so that I can use it anywhere?
class mainClass {
function myForm() {
echo '<input type="text" value="'.$userName.'" />';
}
}
function mainFunction () {
$myArray = array (
'child_of' => $GLOBALS['userName']
)
}
class mainClass {
public $username;
function __construct($username){
$this->username = $username;
}
function myForm() {
echo '<input type="text" value="'.$this->userName.'" />';
}
}
function mainFunction () {
$myArray = array (
'child_of' => $this->username;
);
}
can value of 'userName' be available out side 'mainClass' so that I can use it anywhere?
Yes.
First, you need to define a class property like this
class MainClass
{
private $_userName;
public function myForm()
{
echo '<input type="text" value="'.$this->_userName.'" />';
}
}
Look at how you access this property inside the myForm() method.
Then you need to define getter method for this property (or you can make the property public) like this:
class MainClass
{
private $_userName;
public function getUserName()
{
return $this->_userName;
}
public function myForm()
{
echo '<input type="text" value="'.$this->_userName.'" />';
}
}
You can access user name property like this
$main = new MainClass();
$userName = $main->getUserName();
Note that you need an instance of the MainClass class.
I suggest you to start with simple concept and make sure you understand this 100%. Also I would suggest avoid using global variables and more complicated logic with static methods. Try to make it as simple as possible.
Warm regards,
Victor
The below code is a very minimized version of the Codeigniter get_instance method. So in your case you can have somewhere at the beginning this code:
/** Basic Classes to load the logic and do the magic */
class mainInstance {
private static $instance;
public function __construct()
{
self::$instance =& $this;
}
public static function &get_instance()
{
return self::$instance;
}
}
function &get_instance()
{
return mainInstance::get_instance();
}
new mainInstance();
/** ----------------------------------------------- */
and then you can create your global Classes like this:
class customClass1 {
public $userName = '';
function myForm() {
return '<input type="text" value="'.$this->userName.'" />';
}
}
/** This is now loading globally */
$test = &get_instance();
//If you choose to actually create an object at this instance, you can call it globally later
$test->my_test = new customClass1();
$test->my_test->userName = "johnny";
/** The below code can be wherever in your project now (it is globally) */
$test2 = &get_instance();
echo $test2->my_test->myForm()."<br/>"; //This will print: <input type="text" value="johnny" />
echo $test2->my_test->userName; //This will printing: johnny
As this is now globally you can even create your own function like this:
function mainFunction () {
$tmp = &get_instance();
return $tmp->my_test->userName;
}
echo mainFunction();

Categories