I recently begun to use classes. I've been using procedural programming for quite a while so it has been a bit challenging.
My question.
If I have a class like this:
class Example {
public $name;
public $whatever;
public $yearAdded
public function __construct($name, $whatever=NULL, $dateAdded)
{
some trival code here;
}
}
How can I make $yearAdded use a global variable I set up somewhere else in another script?
FOR EXAMPLE:
global $currentYear = date('Y');
Would I have to do this way
new example($name, $whatever, $currentTime);
or is there a way to specify within the class to always use $currentYear for $yearAdded.
The global keyword doesn't work the way you think it does. It does not make a variable have global scope. All it does is specify to the function that you call it in that you want to use the variable in the outer scope.
For example:
$a="test";
function something() {
global $a;
echo $a; //Outputs: test
}
If you want to make a variable global so that it can be accessed from within a class, you need to use the $GLOBALS superglobal.
http://www.php.net/manual/en/reserved.variables.globals.php
This is not considered to be the best OOP way of doing things, but will get the job done.
You already have a builtin time() function, so why do you need a home-grown global variable in your constructor?
If you think carefully about how you are using globals, you'll find out that there are usually better ways of accessing the same info -- e.g. system environment variables, configuration files, etc.
Related
I have six functions that require a global variable. In an attempt to reduce redundancy, I wrote a new function that is triggered rather than triggering all six. This one function has a global $var that is required by the other functions.
So, it looks like this
function one_function_for_the_rest() {
global $importantVar;
functionOne();
functionTwo();
functionThree();
}
but the global variable is not being seen by the called functions. Am I doing this incorrectly, or is this a limitation I was not aware of?
You're not doing it correctly as the variable is defined when on_function_for... is called. An easier way for this would be just to have $importantVar; at the start of the code.
Or wrap your functions inside a class and put the variable inside the class.
e: so basically do : function myFunc($important) { stuff } and when calling the function do myFunc($importantVar)
example :
$asd = "lol";
class myclass {
public function lol($asd) {
echo $asd;
}
}
$obj = new myclass;
$obj->lol($asd);
You're not doing it correctly. Each function either needs to use the global scope identifier, like global $importantVar;, or have $importantVar passed as a parameter. Otherwise, the other functions don't have $importantVar in their respective scopes.
Simply calling a function from within one_function_for_the_rest does not tell that other function anything about global variables or variables used in one_function_for_the_rest. In technical terms, your function calls do not bring $importantVar into the respective scopes of functionOne, functionTwo, or functionThree.
PHP does not have the same scoping rules as most other languages have. That is the downside to not having to declare variables with var as in JavaScript or other similar constructs.
Basically in PHP, every function used is only available in that function. There are three exceptions:
The global keyword
The $this variable inside objects. This one is also "magic" as it's also available inside anonymous functions defined inside a class.
When declaring an anonymous functions you can bind variables to it using use.
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;
}
}
Is there a way to forbid a variable from being picked out of global scope?
Something like:
#index.php
$forbidden = 'you should not be able to access me outside this scope'; // maybe invoke a function or namespaces?
require 'stuff.php';
echo new stuff();
#stuff.php
class stuff
{
public function __toString()
{
global $forbidden; // to result in an error or something?
/*
just a random example, but yes, any way
to somehow make a variable not global?
*/
return 'I am forbidden';
}
}
Have no idea if it's possible, but anyways, interested in OOP only fashion.
Reason?
To disallow a specific class from being instantiated into a variable and then taken out from global scope to reuse it's functions. Make class completely "private", kind of like a master class that does all the automation.
Hope I've made myself clear.
The only way I can think of would be to "fake" global scope...
//index.php
function scope() {
require 'actual.php';
}
scope();
and now, putting code in actual.php looks like "normal" code but it actually is inside function scope. Obviously you can't declare functions or classes in actual.php now, but otherwise it behaves the same, with the exception that any variables declared will be in the function's scope instead of global scope.
I really wouldn't do this though. A beating with a stick usually works if someone does something stupid like globals like that ;)
my functions.php file is just a placeholder for many different functions. I have another file settings.php that I use to store different settings. Some of the functions in functions.php will need to access some of the variables in settings.php, so I tried:
require("settings.php")
on top of the functions.php file, but that does not seem to give my functions access to the variable in settings.php. I need to put require("settings.php") in every function separately.
Is there a way I can declare the variables in settings.php to be accessible globally to all functions defined in functions.php?
Thank you,
You need to modify your functions in functions.php to use global variables defined in settings.php.
Inside settings.php;
$var1 = "something";
$var2 = "something else";
By using the global keyword:
function funcName() {
global $var1;
global $var2;
// Rest of the function...
}
Or more preferably, using the $GLOBALS[] superglobal array. Any variables declared at global scope, like I assume your settings.php vars are, will be included as array keys in $GLOBALS[]. It's a little better for readability than using the global keyword inside each function.
function funcName() {
$y = $GLOBALS['var1'];
$x = $GLOBALS['var2'];
// Etc...
}
Although you've set these variables in your settings.php file, when you try to reference them in your functions it won't work. This is because variables in functions a locally scoped to the function.
To access these global variables you need to use the global keyword to bring your global variables into scope.
For example:
// Declared in settings.php
$x = 1234;
// One of your functions
function MyFunc()
{
global $x;
DoSomething($x);
}
You need to do this for every function where $x is accessed.
For more information see:
Variable scope - php.net docs
I do not know the details of your issue, but you may wish to use require_once() within each function. This seems to be better idea than using some global variables.
You're thinking global variables.
However that's not the best way to go.
Can you perhaps create a class?
class SomeClass
{
private $settings;
function __construct()
{
require_once($settings);
$this->settings = $variable(s) from settings file
}
function some_function()
{
print($this->settings['something']);
}
}
inside of a function i have a $connection var what obviously stores my connection to mysql,
how can i call that var from inside other functions to save me having to paste the $connection var inside of every function that requires this var?
i have tried global to no avail.
many thanks
You could use the old global keyword.
function a() {
global $connection;
}
Or you could throw it in $GLOBALS (this will help you get it out of the function defined it in).
Neither of them are too pretty.
Or you could pass in the $connection as an argument.
The most common way of dealing with a database connection is to have its creation handled by a singleton pattern, or have a base class with OO that has a $this->db available, that all your other classes can inherit from.
Pass the connection as a parameter to the functions that need it. It keeps your code clean and re-usable.
Another solution would be to use a class and make the connection a class variable. You will just use $this->connection every time you need this, but this is not really a solution if you already have a lot of code written in a lot of files.
Declare the variable outside the function, then make it accessible inside each function you need it by using the global keyword.
$globalName = "Zoe";
function sayHello() {
$localName = "Harry";
echo "Hello, $localName!";
global $globalName;
echo "Hello, $globalName!";
}
sayHello();
stolen from http://www.elated.com/articles/php-variable-scope-all-you-need-to-know/