PHP class: Global variable as property in class - php

I have a global variable outside my class = $MyNumber;
How do I declare this as a property in myClass?
For every method in my class, this is what I do:
class myClass() {
private function foo() {
$privateNumber = $GLOBALS['MyNumber'];
}
}
I want this
class myClass() {
//What goes here?
var $classNumber = ???//the global $MyNumber;
private function foo() {
$privateNumber = $this->classNumber;
}
}
EDIT: I want to create a variable based on the global $MyNumber but
modified before using it in the methods
something like: var $classNumber = global $MyNumber + 100;

You probably don't really want to be doing this, as it's going to be a nightmare to debug, but it seems to be possible. The key is the part where you assign by reference in the constructor.
$GLOBALS = array(
'MyNumber' => 1
);
class Foo {
protected $glob;
public function __construct() {
global $GLOBALS;
$this->glob =& $GLOBALS;
}
public function getGlob() {
return $this->glob['MyNumber'];
}
}
$f = new Foo;
echo $f->getGlob() . "\n";
$GLOBALS['MyNumber'] = 2;
echo $f->getGlob() . "\n";
The output will be
1
2
which indicates that it's being assigned by reference, not value.
As I said, it will be a nightmare to debug, so you really shouldn't do this. Have a read through the wikipedia article on encapsulation; basically, your object should ideally manage its own data and the methods in which that data is modified; even public properties are generally, IMHO, a bad idea.

Try to avoid globals, instead you can use something like this
class myClass() {
private $myNumber;
public function setNumber($number) {
$this->myNumber = $number;
}
}
Now you can call
$class = new myClass();
$class->setNumber('1234');

Simply use the global keyword.
e.g.:
class myClass() {
private function foo() {
global $MyNumber;
...
$MyNumber will then become accessible (and indeed modifyable) within that method.
However, the use of globals is often frowned upon (they can give off a bad code smell), so you might want to consider using a singleton class to store anything of this nature. (Then again, without knowing more about what you're trying to achieve this might be a very bad idea - a define could well be more useful.)

What I've experienced is that you can't assign your global variable to a class variable directly.
class myClass() {
public $var = $GLOBALS['variable'];
public function func() {
var_dump($this->var);
}
}
With the code right above, you get an error saying "Parse error: syntax error, unexpected '$GLOBALS'"
But if we do something like this,
class myClass() {
public $var = array();
public function __construct() {
$this->var = $GLOBALS['variable'];
}
public function func() {
var_dump($this->var);
}
}
Our code will work fine.
Where we assign a global variable to a class variable must be inside a function. And I've used constructor function for this.
So, you can access your global variable inside the every function of a class just using $this->var;

What about using constructor?
class myClass {
$myNumber = NULL;
public function __construct() {
global myNumber;
$this->myNumber = &myNumber;
}
public function foo() {
echo $this->myNumber;
}
}
Or much better this way (passing the global variable as parameter when inicializin the object - read only)
class myClass {
$myNumber = NULL;
public function __construct($myNumber) {
$this->myNumber = $myNumber;
}
public function foo() {
echo $this->myNumber;
}
}
$instance = new myClass($myNumber);

If you want to access a property from inside a class you should:
private $classNumber = 8;

I found that globals can be used as follows:
Create new class:
class globalObj{
public function glob(){
global $MyNumber;
return $this;
}
}
So, now the global is an object and can be used in the same way:
$this->glob();

class myClass
{
protected $foo;
public function __construct(&$var)
{
$this->foo = &$var;
}
public function foo()
{
return ++$this->foo;
}
}

Related

How can I limit the scope of a variable to a single file?

I have several functions which share common variables. But I don't want to keep passing these variables between all the functions, because that means all functions will have a lot of parameters and I find that hard to read.
So I want to define 'global' variables only for these functions, something like so:
$varA;
$varB;
$varC;
function funcA() {
..
}
function funcB() {
..
}
function funcC() {
..
}
As opposed to the ugly way of funcA declaring the variables and functions passing them around between them (resulting in many parameters for each function).
However I want the variables to not be global to all files in the program. Only accessible in this file.
What is the best or most common way to achieve something like this?
If you don't really want to build objects, but only want to have a private scope, you could use static class:
<?php
class Example {
private static $shared_variable;
/* disable the constructor to create a static class */
private function __construct() {}
static function funcA() {
self::$shared_variable = 'AVAILABLE HERE';
}
static function funcB() {
echo self::$shared_variable;
}
}
Example::funcA();
Example::funcB();
// echo Example::$shared_variable; // but not here
I added the private delaration of constructor to prevent the object creation (thus declaring the class static).
I would create a class and refactor the functions to methods and the variables to parameters:
Class newClass
{
private $varA;
private $varB;
private $varC;
public function funcA()
{
$varB = $this->varB;
}
public function funcB()
{
$varC = $this->varC;
}
public function funcC()
{
$varA = $this->varA;
}
}
This way you will have full access to all the set parameters in all your subsequent methods. You can write a setter or create a constructor to add a value to your parameters:
Class newClass
{
public function __construct($varA, $varB, $varC)
{
$this->varA = $varA;
$this->varB = $varB;
$this->varC = $varC;
}
}
This is how I would handle the local scope. Good luck!
The proper way of encapsulating variables and functions which depends on these variables is by using a class.
class MyClass
{
private $varA;
private $varB;
private $varC;
public function __construct($varA, $varB, $varC)
{
$this->varA = $varA;
$this->varB = $varB;
$this->varC = $varC;
}
public function funcA()
{
$localVarB = $this->varB;
}
public function funcB()
{
$localVarC = $this->varC;
}
public function funcC()
{
$localVarA = $this->varA;
}
}
To use this class you must first create an instance of it:
$classInstance = new MyClass("varA", "varB", "value");
$classInstance->funcA();
$classInstance->funcB();
...
More information about classes in php can be found here: http://php.net/manual/en/keyword.class.php

How to access a variable defined out side into inside a class function

My code is
$var = md5(rand(1,6));
class Session{
protected $git;
public function __construct($config = array())
{
//// some code
}
public function _start_session()
{
//code again..
}
}
I want to use the "$var" value inside class functions as globally.
please update me how to do this.
You could use dependency injection. where you pass the required variables to the constructor
$var = md5(rand(1,6));
$session = new Session($var);
$session->_start_session();
class Session{
public function __construct($var, $config = array())
{
$this->var = $var;
}
public function _start_session()
{
echo $this->var;
//code again..
}
}
You can feel free to use variable, defined in global context (with keyword global).
But your example is not a good idea. When you want to change behavior or name of $var, you should rewrite all codes...
Try to use function wrap or even static class to globalize Your variable $var.
functions outside any class are global an can be called from anywhere. The same with variables.. just remember to use the global for the variables.
$var = md5(rand(1,6));
class Session{
protected $git;
public function __construct($config = array())
{
global $var;
//// some code`
}
public function _start_session()
{
//code again..
}
}
define your $var as global and then use directly
like this..
<?php
function abc() { }
$foo = 'bar';
class SomeClass {
public function tada(){
global $foo;
abc();
echo 'foo and '.$foo;
}
}
?>

__get and __set magic methods not accessible

I have a class 'base' and a class 'loader', which looks like this.
class base {
protected $attributes = Array();
public $load = null;
function __construct() {
$this->load = loader::getInstance();
echo $this->load->welcome(); //prints Welcome foo
echo $this->load->name; //prints Foo
echo $this->name; //doesnt print anything and i want it to print Foo
}
public function __get($key) {
return array_key_exists($key, $this->attributes) ? $this->attributes[$key] : null;
}
public function __set($key, $value) {
$this->attributes[$key] = $value;
}
}
class loader {
private static $m_pInstance;
private function __construct() {
$this->name = "Foo";
}
public static function getInstance() {
if (!self::$m_pInstance) {
self::$m_pInstance = new loader();
}
return self::$m_pInstance;
}
function welcome() {
return "welcome Foo";
}
}
$b = new base();
Now what I want is a way to store variables from loader class and access them from base class using $this->variablename.
How can I achieve this? I don't want to use extends. Any idea ?
I don't feel like you've fully understood what coding the OOP way means. And usually Singletons are code smells so I'll just warn you:
There's probably a better way of accomplish you goal. If you provide more informations we will help you out. In its current form the answer is the following; just remember that I higly discourage its implementation in your code.
Assuming that you want to access only public (and non static) loader's variables as this->varname in the base class you should just insert this line in the beginning of the base class constructor:
$this->attributes = get_object_vars(loader::getInstance());
This will basically initialize the attributes array with all the loader public vars so that via your __get() method you can access its value.
On a side note, take a look at Dependency Injection design pattern in order to avoid using Singletons.
Your __get/__set methods access $this->attributes but not $this->load.
You could e.g. do something like (pseudocode)
function __get($key) {
- if $attribute has an element $key->$value return $attribute[$key] else
- if $load is an object having a property $key return $load->$key else
- return null;
}
see also: http://docs.php.net/property_exists
You can make static variable and then you can access this variable from anywhere
public statis $var = NULL;
and you can access it like this
classname::$var;

Calling static class member in PHP

I am trying to get a variable from a php class without having to use "new classname()"
This is my code:
class myVars {
static $varx = null;
public function __construct() {
$this->varx = "test";
}
}
echo myVars::$varx;
I also tried replacing $this-> with self::, but nothing gets printed. How should I code the class in order to call myVars::$varx?
The problem you are having, is that you are not instantiating an object, so the constructor never gets called.
What you could do is:
class myVars {
static $varx = null;
public function __construct() {
$this->varx = "test";
}
}
myVars::$varx = "test";
echo myVars::$varx;
Or you could create an object and have the constructor change the static variable.
This should make your static variable publicly accessible.
class myVars {
public static $varx = null;
public function __construct() {
self::$varx = "test";
}
}
echo myVars::$varx;
However, in your example, the constructor is never called, so the modification to the static variable is never made.

assign function to class method

Is it possible to create a function out of a class method?
ie.
class Test {
public function __construct()
{
if ( ! function_exists('foo') ) {
function foo ()
{
return $this->foo();
}
}
}
private function foo()
{
return 'bar';
}
}
Or would I have to do it the other way around, creating a function and using it within the method?
Just do it like that, php is able to do it
class Test {
public function __construct()
{
if ( ! function_exists('foo') ) {
function foo ()
{
return $this->foo();
}
}
}
private function foo()
{
outsidefunction();
return 'bar';
}
}
private function outsidefunction()
{
return 0;
}
i'm trying to create a global function that is a copy of the class method. I come from javascript land where functions are just variables and you can easily copy them...
Functions in PHP are not first class citizens, you cannot copy functions around like variables in PHP. You can hand a reference to a function around, but not the function itself.
In theory, you could use Reflection to get a Closure, reference it via $GLOBALS and then define a function foo to call the Closure from $GLOBALS, e.g.
<?php // requires 5.4
class Test {
public function __construct()
{
if (!function_exists('foo')) {
$reflector = new ReflectionMethod(__CLASS__, 'foo');
$GLOBALS['foo'] = $reflector->getClosure($this);
function foo() {
return call_user_func($GLOBALS['foo']);
}
}
}
private function foo()
{
return 'bar';
}
}
$test = new Test();
echo foo();
Run Demo
However, that is extremely ugly and you do not want to do it this way.
If you want more JavaScript like objects, have a look at
http://www.phpied.com/javascript-style-object-literals-in-php
But still, even the suggested techniques in there are kludges imo.

Categories