This question already has answers here:
DEFINE vs Variable in PHP
(5 answers)
Closed 9 years ago.
by define I mean using define function.
What I want to know is can I shorten this:
$GLOBALS['MY_VAR'] to MY_VAR ... and use it in any scope! (not having to use global $myvar; in functions).
EDIT:
example: print_r(MY_VAR['somekey']); gives error!
EDIT:
I understand it makes a constant variable, but isn't it a constant pointer to the array? I thought arrays are mutable in php?
Define refers to a constant and not a global. Constants can be used anywhere. Below is how you would use it with the example you gave.
define( 'MY_VAR', $GLOBALS['MY_VAR'] );
More info here: http://uk1.php.net/define
Hm, is it always a constant? I guess a better way is you build your own token. If you do so, you can access from anywhere your token and edit, read or change the values within this token.
For your needs, build a token class (just copy and paste it to file named MyTokenHolder.php):
class MyTokenHolder
{
protected static $_sessionkey = "BE SURE TO OVERRIDE THIS KEY";
//Define your values here
public $Username;
public $UserID;
public function __construct()
{
if(isset($_SESSION[self::$_sessionkey]))
{
$token = unserialize(base64_decode($_SESSION[self::$_sessionkey]));
//see above public params
$this->Username = $token->Username;
$this->UserID = (int)$token->UserID;
}
}
public function SaveToSession()
{
$_SESSION[self::$_sessionkey] = base64_encode(serialize($this));
}
public static function DestroySession()
{
unset($_SESSION[self::$_sessionkey]);
}
}
Now, you can set the values, which are defined within the token:
//Set Values
$token = new MyTokenHolder();
$token->Username = 'test';
$token->UserID = 99;
$token->SaveToSession();
And also you can read your values from token.
//Read Values
$token = new MyTokenHolder();
echo $token->UserID;
echo $token->Username;
Test your self here - SQL Fiddle: http://ideone.com/jj7r6l
Try this :
define("CONSTANT","anything");
and you can use CONSTANT anywhere in any scope.
example :
define("CONSTANT","123abc321");
function test(){
return CONSTANT;
}
echo test(); //echoes 123abc321
But
Note that you can't assign an array to a constant value.
Related
How to make function from string? I am new to php programming and wanted solution for below code.
If I want to access page for test2.php?page=test for below class:
class test{
public static function getTest(){
//code here....
};
}
and wanted to access test2.php?page=test using variable so what should I do?
require_once "test.php";
$variabe = $_GET['page'];
test::get . ucfirst($variable) . ();
You can do it like this:
<?php
class test{
public static function getTest(){
echo 'getTest()!!';
}
}
$variable = 'Test';
// since we are interpolating a raw string, input from $_GET, and a function we need to let PHP know to fully complete this string before using it as a function call
test::{"get".ucfirst($variable)}();
// Build the full method name ahead of time and you can just call it using the variable
$variable2 = 'getTest';
test::$variable2();
Output:
getTest()!!
This question already has answers here:
Function literal in PHP class
(3 answers)
Closed 6 years ago.
This is my code:
class Config {
static public $site = 'http://localhost/site/';
static public $style = $site . 'css/style.css';
// ...
}
This is not work for me. I get white screen.
class Config {
static public $site = 'http://localhost/site/';
static public $style = 'http://localhost/site/css/style.css';
// ...
}
This is work. I get design and code. Work very well. My question is Why?
This is not possible:
static public $style = $site . 'css/style.css';
Expressions cannot be used to initialize class values. Only constant values are permitted. This is something you'd have to do in the constructor, but since they're static values, there's no guarantee that the object will have been initialized BEFORE you try to access those statics.
class foo {
public $foo = 1; // ok
public $bar = 1+1; // ok only in PHP 5.6+
public $baz = $this . $that; // not valid in any version of PHP
The only time you could use expressions (in php 5.6+) is if the resulting value can be calculated at compile time. so 1+1 is ok, because that can be handled at compile time. but $this . $that can only be determined at runtime, and is therefore illegal.
I'm new to PHP and practicing using static variables. I decided to grab an example that I learnt from C++ and re-write it for PHP (example from the bottom of this article).
There's a class with two private variables (one static), a constructor and a get-method. The constructor assigns the static variable's value to the second private variable, and then increments.
<?php
class Something
{
private static $s_nIDGenerator = 1;
private $m_nID;
public function Something() {
$m_nID = self::$s_nIDGenerator++;
echo "m_nID: " . $m_nID . "</br>"; //for testing, can comment this out
}
public function GetID() {
return $m_nID;
}
}
// extra question:
// static variable can be assigned a value outside the class in C++, why not in PHP?
// Something::$s_nIDGenerator = 1;
$cFirst = new Something();
$cSecond = new Something();
$cThird = new Something();
echo $cFirst->GetID() . "</br>";
echo $cSecond->GetID() . "</br>";
echo $cThird->GetID() . "</br>";
?>
Using the echo test in line 9 to see if m_nID is getting a value I see:
m_nID: 1
m_nID: 2
m_nID: 3
But these values are not being returned by the "->GetID()" calls. Any ideas why?
Edit: both replies so far have solved this, I wish I could "check" them both, so thank you! I'll leave the original code in the question as-is for any future people who have a similar problem
Your background in C++ led up to this issue, which is an easy mistake to make. In PHP, all instance (or object) variables are referenced using $this->, and static (or class) variables with self::. Based on your code:
public function GetID() {
return $m_nID;
}
Access to the private variable $m_nID should be scoped like this:
public function GetID() {
return $this->m_nID;
}
And inside your constructor:
$m_nID = self::$s_nIDGenerator++;
It should have been:
$this->m_nID = self::$s_nIDGenerator++;
Q & A
Why is there no need to put $ before m_nID when using $this->
The above two ways of referencing instance and class variables come with a very different kind of syntax:
$this is the instance reference variable and any properties are accessed using the -> operator; the $ is not repeated for the property names themselves, although they're present in the declaration (e.g. private $myprop).
self:: is synonymous to Something:: (the class name itself); it doesn't reference an instance variable and therefore has no $ in front of it. To differentiate static variables from class constants (self::MYCONST) and class methods (self::myMethod()) it's prefixed with a $.
Extra
That said, $this->$myvar is accepted too and works like this:
private $foo = 'hello world';
function test()
{
$myvar = 'foo';
echo $this->$foo; // echoes 'hello world'
}
class Something{
private static $s_nIDGenerator = 1;
private $m_nID;
public function Something() {
$this->m_nID = self::$s_nIDGenerator++;
}
public function GetID() {
return $this->m_nID;
}
}
It is interesting to note the difference between using self::$s_nIDGenerator on a static variable vs using $this->s_nIDGenerator on a static variable, whereas $this-> will not store anything.
I'm trying to get a static class variable to expand/resolve inside of a HEREDOC expression within a class constructor, but I cannot find a way to make it work. Please see my very simplified example below:
class foo {
private static $staticVar = '{staticValue}';
public $heredocVar;
public function __construct() {
$this->heredocVar = <<<DELIM
The value of the static variable should be expanded here: {self::$staticVar}
DELIM;
}
}
// Now I try to see if it works...
$fooInstance = new foo;
echo $fooInstance->heredocVar;
Which results in the following output:
The value of the static variable should be expanded here: {self::}
Additionally, I've tried various methods to reference the static variable without luck. I'm running PHP version 5.3.6.
Edit
As pointed out by Thomas, it is possible to use an instance variable to store a reference to the static variable, and subsequently use that variable inside the HEREDOC. The following code is ugly, but it does work:
class foo {
private static $staticVar = '{staticValue}';
// used to store a reference to $staticVar
private $refStaticVar;
public $heredocVar;
public function __construct() {
//get the reference into our helper instance variable
$this->refStaticVar = self::$staticVar;
//replace {self::$staticVar} with our new instance variable
$this->heredocVar = <<<DELIM
The value of the static variable should be expanded here: $this->refStaticVar
DELIM;
}
}
// Now we'll see the value '{staticValue}'
$fooInstance = new foo;
echo $fooInstance->heredocVar;
What about this answer?
I would set $myVar = self::$staticVar; and then use $myVar in the HEREDOC code.
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...