PHP - accessing global variables in all functions of class - php

I need to access some variables of an external php file in most of functions of a class. I'm accessing in following way (and it works fine)
class test{
function a(){
global $myglobalvar ;
..
..
}
function b(){
global $myglobalvar ;
..
..
}
function c(){
global $myglobalvar ;
..
..
}
}
Is there a way that i can access $myglobalvar in all functions of the class without declaring in each function? I did read that it can be done by declaring only once in the constructor of the class, but I dont know how to do it.
Thanks for any help.

class test{
private $myglobalvar;
public function __construct($var){
$this->myglobalvar = $var;
}
function a(){
echo $this->myglobalvar;
}
function b(){
echo $this->myglobalvar;
}
function c(){
echo $this->myglobalvar;
}
}
$test = new test("something");
$test->a(); // echos something
$test->b(); // echos something
$test->c(); // echos something

You can create a reference to a global variable in the constructor (much like global would):
class test{
function __construct() {
$this->myglobalvar = & $GLOBALS["myglobalvar"];
Which then allows aceess to the global via $this->myglobalvar in each method.

If you tell us more about this case, we might be able to tell you a better way to solve your problem. Globals should be avoided, whenever possible. Are you really talking about a variable or is it more like a configuration option that stays the same during a whole server roundtrip. In that case you could think of treating it like a configuration option and store it in a registry object (singleton).

Related

Nested function property accessibility

I want to access testProperty in the below example, but this is inside a nested function (extending twig, it has to be nested), but it of course says
"Using $this when not in object context".
I simply can't open another 'public function' inside an existing one. Does anyone know how to fix this?
I want a global variable in the entire class, without using global.
class test
{
private testProperty;
public function testFunction() {
function abc() {
var_dump($this->testProperty)
}
}
}
I didn't fix the problem exactly as I wanted it stated, but I did fix it in my document. I placed my function outside and made it public and just changed al my abc() to $this->abc() really dumb oversight of mine
If my guess of what you're trying to achieve is correct, you may want to do something like this:
class test
{
private $testProperty = "whatever";
public function testFunction() {
$abc = function() {
var_dump($this->testProperty);
};
$abc();
}
}
$x = new test;
$x->testFunction();
Since $abc is now an anonymous function, it has $this variable available when used inside a class method.
The code above will output:
string(8) "whatever"

Access a class within a function

Using as an example the class defined here
class Testclass {
private $testvar = "default value";
public function setTestvar($testvar) {
$this->testvar = $testvar;
}
public function getTestvar() {
return $this->testvar;
}
function dosomething()
{
echo $this->getTestvar();
}
}
$Testclass = new Testclass();
$Testclass->setTestvar("another value");
$Testclass->dosomething();
I would like to add inside a function "one more value", like this:
function test_function() {
$Testclass->setTestvar("one more value");
}
But it doesn´t work. I gives the error message undefined variable Testclass. In order to make it work, I have to define the variable as global within the function, like this:
function test_function() {
global Testclass;
$Testclass->setTestvar("one more value");
}
I am quite new to PHP, but it seems rather strange to me this way of using it. From the main PHP file it´s already defined, but when I use it from a function I have to define again.Basically what I am trying to do is to create a class that creates a new file and adds strings to it from different functions. Is there not a better way? Any suggestions? Many thanks in advance.
One way is to use singleton
MyClass::getInstance()->doSomethingUsefull();
Sometimes you can use static method
MyClass::doIt();
Functions have their own private variable scope. So (for example) you can use $i in a function without worrying about it screwing up another $i somewhere else in the program. If you want to have a function perform actions on an already-existing object, just pass the object as a parameter to the function:
function test_function(Testclass $testclass)
{
$testclass->setTestvar("one more value");
}
Then call it with your object:
$Testclass = new Testclass();
test_function($Testclass);
Note: If the functions you're defining outside the class are tightly related to the class, then you probably want to define them as methods inside the class instead of separate stand-alone functions.

How to Pass a function to a class in php

I have a class that generates data based on a few things. I would like to format that data from the outside. So I am trying to pass a function into the class so that it would format that data. I have looked at many examples, but it seems this is unique.
Can anybody give an idea of how to do this? The following code gives an error.
<?php
class someClass {
var $outsideFunc; // placeholder for function to be defined from outside
var $somevar='Me'; // generated text
function echoarg($abc){
$outsideFunc=$this->outsideFunc; // bring the outside function in
call_user_func($outsideFunc,$abc); // execute outside function on text
echo $abc;
}
}
function outsidefunc($param){ // define custom function
$param='I am '.$param;
}
$someClass=new someClass();
$someClass -> outsideFunc = 'outsideFunc'; // send custom function into Class
$someClass -> echoarg($someClass->somevar);
$someClass -> outsidefunc = 'outsidefunc';
In PHP, function names are not case sensitive, yet object property names are. You need $someClass->outsideFunc, not $someClass->outsidefunc.
Note that good OOP design practice calls for the use of getter and setter methods rather than just accessing properties directly from outside code. Also note that PHP 5.3 introduced support for anonymous functions.
Yeah. You are right. Now there is no error. But it does not work either.
By default, PHP does not pass arguments by reference; outsidefunc() does not actually do anything useful. If you want it to set $param in the caller to something else, and do not want to just return the new value, you could change the function signature to look like this:
function outsidefunc(&$param) {
You would also need to change the way you call the function, as call_user_func() does not allow you to pass arguments by reference. Either of these ways should work:
$outsideFunc($abc);
call_user_func_array($outsideFunc, array(&$abc));
Why not pass your function as an argument?
<?php
class someClass {
public $somevar="Me";
public function echoarg($abc,$cb=null) {
if( $cb) $cb($abc);
echo $abc;
}
}
$someClass = new someClass();
$someClass->echoarg($someClass->somevar,function(&$a) {$a = "I am ".$a;});
i am not sure what exactly you are looking for, but what i get is, you want to pass object in a function which can be acheive by
Type Hinting in PHP.
class MyClass {
public $var = 'Hello World';
}
function myFunction(MyClass $foo) {
echo $foo->var;
}
$myclass = new MyClass;
myFunction($myclass);
OP, perhaps closures are what you're looking for?
It doesn't do EXACTLY what you're looking for (actually add function to class), but can be added to a class variable and executed like any normal anonymous function.
$myClass->addFunc(function($arg) { return 'test: ' . $arg });
$myClass->execFunc(0);
class myClass {
protected $funcs;
public function addFunc(closure $func) {
$this->funcs[] = $func;
}
public function execFunc($index) { $this->funcs[$index](); } // obviously, do some checking here first.
}

PHP access external $var from within a class function

In PHP, how do you use an external $var for use within a function in a class? For example, say $some_external_var sets to true and you have something like
class myclass {
bla ....
bla ....
function myfunction() {
if (isset($some_external_var)) do something ...
}
}
$some_external_var =true;
$obj = new myclass();
$obj->myfunction();
Thanks
You'll need to use the global keyword inside your function, to make your external variable visible to that function.
For instance :
$my_var_2 = 'glop';
function test_2()
{
global $my_var_2;
var_dump($my_var_2); // string 'glop' (length=4)
}
test_2();
You could also use the $GLOBALS array, which is always visible, even inside functions.
But it is generally not considered a good practice to use global variables: your classes should not depend on some kind of external stuff that might or might not be there !
A better way would be to pass the variables you need as parameters, either to the methods themselves, or to the constructor of the class...
Global $some_external_var;
function myfunction() {
Global $some_external_var;
if (!empty($some_external_var)) do something ...
}
}
But because Global automatically sets it, check if it isn't empty.
that's bad software design. In order for a class to function, it needs to be provided with data. So, pass that external var into your class, otherwise you're creating unnecessary dependencies.
Why don't you just pass this variable during __construct() and make what the object does during construction conditional on the truth value of that variable?
Use Setters and Getters or maybe a centralized config like:
function config()
{
static $data;
if(!isset($data))
{
$data = new stdClass();
}
return $data;
}
class myClass
{
public function myFunction()
{
echo "config()->myConfigVar: " . config()->myConfigVar;
}
}
and the use it:
config()->myConfigVar = "Hello world";
$myClass = new myClass();
$myClass->myFunction();
http://www.evanbot.com/article/universally-accessible-data-php/24

create superglobal variables in php?

is there a way to create my own custom superglobal variables like $_POST and $_GET?
Static class variables can be referenced globally, e.g.:
class myGlobals {
static $myVariable;
}
function a() {
print myGlobals::$myVariable;
}
Yes, it is possible, but not with the so-called "core" PHP functionalities. You have to install an extension called runkit7:
Installation
After that, you can set your custom superglobals in php.ini as documented here:
ini.runkit.superglobal
I think you already have it - every variable you create in global space can be accessed using the $GLOBALS superglobal like this:
// in global space
$myVar = "hello";
// inside a function
function foo() {
echo $GLOBALS['myVar'];
}
Class Registry {
private $vars = array();
public function __set($index, $value){$this->vars[$index] = $value;}
public function __get($index){return $this->vars[$index];}
}
$registry = new Registry;
function _REGISTRY(){
global $registry;
return $registry;
}
_REGISTRY()->sampleArray=array(1,2,'red','white');
//_REGISTRY()->someOtherClassName = new className;
//_REGISTRY()->someOtherClassName->dosomething();
class sampleClass {
public function sampleMethod(){
print_r(_REGISTRY()->sampleArray); echo '<br/>';
_REGISTRY()->sampleVar='value';
echo _REGISTRY()->sampleVar.'<br/>';
}
}
$whatever = new sampleClass;
$whatever->sampleMethod();
One other way to get around this issue is to use a static class method or variable.
For example:
class myGlobals {
public static $myVariable;
}
Then, in your functions you can simply refer to your global variable like this:
function Test()
{
echo myGlobals::$myVariable;
}
Not as clean as some other languages, but at least you don't have to keep declaring it global all the time.
No
There are only built-in superglobals listed in this manual
Not really. though you can just abuse the ones that are there if you don't mind the ugliness of it.
You can also use the Environment variables of the server, and access these in PHP
This is a good way to maybe store global database access if you own and exclusively use the server.
possible workaround with $GLOBALS:
file.php:
$GLOBALS['xyz'] = "hello";
any_included_file.php:
echo $GLOBALS['xyz'];
One solution is to create your superglobal variable in a separate php file and then auto load that file with every php call using the auto_prepend_file directive.
something like this should work after restarting your php server (your ini file location might be different):
/usr/local/etc/php/conf.d/load-my-custom-superglobals.ini
auto_prepend_file=/var/www/html/superglobals.php
/var/www/html/superglobals.php
<?php
$_GLOBALS['_MY_SUPER_GLOBAL'] = 'example';
/var/www/html/index.php
<?php
echo $_MY_SUPER_GLOBAL;
Actually, there is no direct way to define your own superglobal variables; But it's a trick that I always do to access simpler to my useful variables!
class _ {
public static $VAR1;
public static $VAR2;
public static $VAR3;
}
Then I want to use:
function Test() {
echo \_::$VAR2;
}
Notice: Don't forget to use \ before, If you want to use it everywhere you have a namespace too...
Enjoy...

Categories