This question already has answers here:
`static` keyword inside function?
(7 answers)
Closed 9 years ago.
I have seen in 3rd party code a variable declared as static, but outside of any class, simply in a "normal" function.
<?php
function doStuff(){
static $something = null;
}
?>
I have never seen static used this way, and I cannot find anything it in the PHP documentation.
Is this legal PHP code? Is this effectively the same as a global variable? If not, what is the purpose?
From the manual:
Another important feature of variable scoping is the static variable.
A static variable exists only in a local function scope, but it does
not lose its value when program execution leaves this scope.
<?php
function test()
{
static $a = 0;
echo $a;
$a++;
}
?>
Now, $a is initialized only in first call of function and every time
the test() function is called it will print the value of $a and
increment it.
Related
This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 7 years ago.
I declared a new variable $var at the top of my document. Afterwards, I called a function which should output this variable.
Unfortunately, I get the following message:
Notice: Undefined variable: var
This is my code:
$var = "abc";
func ();
function func() {
echo $var;
}
In PHP, functions cannot access variables that are within the global scope unless the keyword global is used to 'import' the variable into the function's scope.
You would fix it by doing this:
function func() {
global $var;
echo $var;
}
Read more about scoping here: http://php.net/manual/en/language.variables.scope.php
Any variable used inside a function is by default limited to the local function scope.
In PHP global variables must be declared global inside a function if they are going to be used in that function.
Global variables can also be accessed using $GLOBALS although I would avoid using that unless absolutely necessary.
A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array.
Worth mentioning:
It's worth linking to this discussion on globals and why you may not want to use them: Globals are evil
. I'd say there is a preference to use classes instead, or simply pass in the variable as an argument to the function. I won't say not to use globals but at the very least be mindful of its use.
This is because the scope of the variable, either you define it as global, or you pass it as a parameter.
Check the comments under this post:
Variables Scope
The scoping of your variable is wrong. You will need to either pass it as a function parameter or declare it as Global in the function. Please review function scoping.
You could do something like this:
$var = "abc";
func ();
function func() {
global var;
echo $var;
}
This question already has an answer here:
Is there a way to disable adding properties into a class from an instance of the class?
(1 answer)
Closed 8 years ago.
I have the following case.
I have a class without variables, which by mistake sets a value to a variable that 'does not exists', in its constructor. The outcome is that the variable is created on the fly and it is viable as long as the class instance exists.
myClass.php
class myClass {
public function __construct($var)
{
$this->var = $var;
}
public function printVar() {
echo $this->var. "</br>";
}
}
tester.php
include("myClass.php");
$myClass = new myClass("variable");
$myClass->printVar();
var_dump($myClass);
And when I run the tester.php the output is the following
variable
object(myClass)#1 (1) { ["var"]=> string(8) "variable" }
Does anyone knows why this is happening? Can you point me to any documentation lemma that explains this behavior?
Is it possible to avoid something like this overloading the __set() function?
It is because php don't make it mandatory to declare before assigning value to it. But you should always declare variable in class as it increases readability of your code and also you can specify accessibility of variable to be public or private.
If you are looking at creating vars on the fly based on a string you pass, you might want to check on $$vars, yes, two time '$' if i got your problem correctly this time
This question already has answers here:
PHP class: Global variable as property in class
(8 answers)
Closed 9 years ago.
I want to know if there is a way to store a global variable inside a class property so that it can be easily used by methods inside the class.
for example:
$variableGlobal = 30;
Class myClass{
public $classProperty = global $variableGlobal;
function myFunction(){
$accessible = $this->classProperty;
}
now I know I can get the global variable by simply calling for it in the class function like so:
function myfunction(){
global $variableGlobal;
}
I thought something like what I want in example 1 existed in but I could be flat out wrong, or I am right but I am approaching this the complete wrong way. Any ideas would be great thanks.
Forgot to mention alternatively I would be happy not to use a global and instead store the results of another class function inside the class variable
like so:
public $var = OtherClass::ClassFunction();
The value you want should be available anywhere in the GLOBALS variable using the variable name as the key.
public $classProperty = GLOBALS[$variableGlobal]
However, I would suggest, to avoid unnecessary coupling and allow for testing, you may want to pass the value in the global in to the class.
You can use the construct method and pass by reference. Inject the value to the constructor when you instantiate the class, and by using reference operator &, you can access the global variable at any time and pick up the current value.
You can also just access the global via $GLOBAL structure within the class. See the example here:
<?php
$variableGlobal = 30;
class myClass{
public $classProperty;
public function __construct(&$globalVar){
$this->classProperty = &$globalVar;
}
public function myFunction(){
$accessible = $this->classProperty;
// do something interesting
print "$accessible\n";
}
public function accessGlobal(){
print $GLOBALS["variableGlobal"] . "\n";
}
}
$thisClass = new myClass($variableGlobal);
$thisClass->myFunction();
$GLOBALS["variableGlobal"] = 44;
$thisClass->myFunction();
$variableGlobal = 23;
$thisClass->accessGlobal();
Recommended reading
References Explained
GlOBALS Explained
Figured it out, used a solution to solve my problem from another question:
PHP class: Global variable as property in class
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Access global variable from within a class
I want to fortify my knowledge in PHP. But most of the time I have trouble understanding with scopes. I am not sure when to use $this and global declaration keyword on my functions.
This is just an example class I just omitted the __construct()
class myClass{
public myVariable;
public function1() {
$this->myVariable=1;
}
public function2(){
global $myVariable;
$myVariable=1;
}
}
Which one is the best approach to use when assigning pre-declared variables inside a function? I am confused somehow by the different books by major publishers in PHP. I am not sure if I am asking the correct question or somehow relevant.
First off, thats not valid PHP, as Jared Farrish already said. Its public $myvar instead of public myvar. Variable names always begin with $.
When you declare a variable in a class:
<?php
class A
{
private $var;
}
That variable will be automatically available in all methods if accessed through $this (unless the method static, but that is another story). So this would work:
<?php
class A
{
private $var;
public function foo () {
// This works
$this->var = 1;
// This is a completely different thing and does not change
// the contents of A::$var
$var = 1;
}
}
Now global is a different thing altogether. In PHP, you cant do this:
<?php
$global_a = 123;
function myfunc ()
{
// You wont actually change the value of $global_a with this
$global_a = 1234;
}
echo $global_a; // still 123
You'd think this would work, but global variables aren't automatically available to functions. This is where global comes in:
<?php
$global_a = 123;
function myfunc ()
{
global $global_a;
$global_a = 1234;
}
echo $global_a; // now it will be 1234
I suggest you read about variable scope in PHP and then you can go on to OOP in PHP.
PHP is a very quirky language. Just because something works in most languages in a certain way doesn't mean it will work in PHP. Most of the times, it wont. So its best to educate yourself as much as possible.
Hope this helps
Which one is best often depends on the situation. In general it's best to avoid global variables as they bring risks with them of not knowing exactly where they're used.
Using a class variable is a good option if the variable is specific to that instance of the class. (You will have to prefix it with a $, though. I.e., public $myVariable;).
If the variable is only relevant to the function and instances outside the class, you'd do best to pass it as an reference. This is done by adding an & before the $ in the parameter space. I.e.:
public function3(&$myVariable) {
$myVariable = 1;
}
Or alternatively just return the value you wish and set it outside the function. I.e.,:
class MyClass {
public function3() {
return 1;
}
}
$myObject = new MyClass();
$myVariable = $myObject->function4();
try to avoid passing global variable,as there are many good reasons for that:
Reusing parts of the script is impossible :
If a certain function relies on global variables, it becomes almost impossible to use that function in a different context. Another problem is that you can’t take that function, and use it in another script.
Solving bugs is much harder :
Tracking a global variable is much harder than a non-global variable.
Understanding the code in a year will be much more difficult :
Globals make it difficult to see where a variable is coming from and what it does.
Now your questions:
Which one is the best approach to use when assigning pre-declared variables inside a function?
You can pass them by value or reference inside a function
By value
$firstVar = 1;
function abc($firstVar){
echo $firstVar ; // will give you 1
}
By reference
function abc(&$firstVar){
$firstVar = 3; // this will give utility to change that variable even
echo $firstVar ; // will give you 3
}
Now where to use $this variable:
$this is used to refer to the current object.
example:
class abc{
private $firstVar;
function abc(){
$this->firstVar = 2;
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
what is the difference between “GLOBAL” and “STATIC” variable in php
if we create a static variable inside a function, this variable exists in further using of the function... and as far as I know global variable does the same.
now what's the benefit of using static variables?
The lexical scope of a static static variable is restricted to the function body – you cannot access the variable outside the function.
However, its value will be remembered across multiple calls of the same function.
Global variables exist in global scope and can be accessed from anywhere in your code (you have to use the global keyword or $GLOBALS array inside functions though)
A static variable just implies that the var belongs to a class but can be referenced without having to instantiate said class. A global var lives in the global namespace and can be referenced by any function in any class. Global vars are always frowned upon because they're so easily misused, overwritten, accidentally referenced, etc. At least with static vars you need to reference via Class::var;