Undefined variable issue in my php project - php

[SOLVED]: I've set a SESSION variable that I can use in the whole project ;)
I already took a look at the variable scope argument on the php manual online,but still I couldn't find a solution to my problem :(
In my controller I've got the following:
if(isset($_POST["idMappaMod"])){//Modifica mappa
$oldmap=$this->model->ottieniindirizzo($_POST["idMappaMod"]);
include'view/modmap.php';
}
After the click on the NewMapAddress button,I want to manage that (again in the controller):
if (isset($_POST["NewMapAdress"])){
$result_map_mod=$this->model->modificamappa($oldmap,$this->user->id,$_POST["NewMapAdress"]);
include'view/modmap.php';
}
I get the undefined variable notice on the $oldmap variable. How can I do? Already tried to declare it outside everythin as global. Did not help.

What about you create a public variable into your class? So you could manage this variable through your instaced class, something like this:
<?php
class YourClass {
public $old;
public function yourFunction() {
$this->old = ...
}
}
$yourClass = new YourClass();
$yourClass->old; // here you have the variable from the instance
?>

Related

Class Property Containing a Global Variable [duplicate]

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

make variable available to all classes, methods, functions and includes, just like $_POST

This question seems simple enough, but I can't find an answer anywhere...
At the beginning of my php script/file I want to create a variable.
$variable = 'this is my variable';
I want this variable to be available within the entire script, so that all classes, methods, functions, included scripts, etc. can simple call this variable as $variable.
Class MyClass
{
public function showvariable()
{
echo $variable;
}
}
The $_SESSION, $_POST, $_GET variables all behave like that. I can just write a method and use $_POST and it'll work. but if I use $variable, which I have defined at the beginning of my script, it says "Notice: Undefined variable: variable in ..." It even says it, when I write a function, rather than a class method...
I tried to write
global $variable = 'this is my variable';
But then the script wouldn't load...
"HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request."
How can I make a variable truly globally accessible like $_POST?
Why would I need this? I specifically plan on using it as a form token. At the top of the page I generate my form token as $token, at the bottom of the page I store it in the session. Before handling any form I check if the SESSION token matches the POST token... And since I often have multiple forms on the page (login form in the top nav, and register form in the main body) i just wanna make it convenient and call $token on each form. Sometimes my formelements are generated by classes or functions, but they don't recognize the variable and say it's not defined.
I found it... -.- I thought it would be easy enough...
I have to call to the variable by using
$GLOBALS['variable'];
Just found it... finally...
http://php.net/manual/en/reserved.variables.globals.php
EDIT like 8 months later or so:
I just learned about CONSTANTS!
define('name', 'value');
They just can't be reassigned...
I guess I could use that, too!
http://www.php.net/manual/en/language.constants.php
Just define a variable outside of any class or function. Then use keyword global inside any class or function.
<?php
// start of code
$my_var = 'Hellow Orld';
function myfunc() {
global $my_var;
echo $my_var; // echoes 'Hellow Orld';
}
function myOtherFunc() {
var $my_var;
echo $my_var; // echoes nothing, because $my_var is an undefined local variable.
}
class myClass {
public function myFunc() {
global $my_var;
echo $my_var; // echoes 'Hellow Orld';
}
public function myOtherFunc() {
var $my_var;
echo $my_var; // echoes nothing.
}
}
myFunc(); // "Hellow Orld"
myOtherFunc(); // no output
myClass->myFunc(); // "Hellow Orld"
myClass->myOtherFunc(); // no output
// end of file
?>
you need to declare global to access it in any function scope:
at the top of your script:
global $var;
$var= "this is my variable";
in your class
...
public function showvariable(){
global $var;
echo $var;
}
...
In PHP, global variables must be declared as such within each function in which they will be used. See: PHP Manual, section on variable scope
That being said, global variables are often a bad idea, and in most cases there's a way to avoid their use.

PHP Function scopes. Trouble coping up with $this vs. global declaration [duplicate]

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;
}
}

Call a non-global variable from a function?

During the development of a Joomla! plugin, I ran across something really interesting. One of the events does not have a return value, but it calls variables from inside the function. Prior knowledge tells me this should only work if the variables are global inside the function, yet the dispatcher is able to call the variables from outside the function.
EDIT: I just discovered that the variable that is accessed from inside the function needs to be one of the paramaters! Could this be func_get_params() or call_user_func()?
Calling Code:
$instance = JDispatcher::getInstance();
$instance->trigger(onJoomCalledEvent, array(&$link, $other_params));
Plugin (snippet):
class plgMyPlugin extends JPlugin{
onJoomCalledEvent($link, $other_params){
$link = "Some Value Here";
return false;
}
}
This function returns false, yet somehow the application (Joomla!) is able to extract the value of $link. How is this done?
Does the plug-in definition look like this:
class plgMyPlugin extends JPlugin{
onJoomCalledEvent(&$link, $other_params){
$link = "Some Value Here";
return false;
}
}
Than it's pass by reference. If it's indeed the way you posted above than it's call time pass by reference which is deprecated and emits a warning starting with PHP 5.3.

"global" does not work in CakePHP 2.1.1 views

I am using PHP 5.3.8 with CakePHP 2.1.1.
This is my view (the layout is empty, actually it only outputs the view itself)
<?php
// $present is not a view variable
$present = 'Hello World!';
class ApplicationsPDF
{
public function CreateApplicationTable()
{
global $present;
exit(var_dump($present));
}
}
$pdf = new ApplicationsPDF();
$pdf->CreateApplicationTable();
?>
The output is null instead of "Hello World!".
If I copy and paste this code into a single file (which I directly run from the browser), it perfectly works!
So it must be a CakePHP bug. Does anyone know it?
Try to declare the global keyword before the class definition:
global $present;
class ApplicationsPDF
{
public function CreateApplicationTable()
{
exit(var_dump($present));
}
}
It's not a PHP nor a CakePHP bug!
It's because CakePHP includes the view in its view class so the declared variables aren't really in the global scope and global has no effect.
From ADmad (source):
When you run the file by itself your assignment $testVar = 'Hello
World!' is in global context hence things work like you expected them
to. But when it is used as a view file, the file is included within a
View class function hence its no longer in global context and $testVar
is no longer a global var, hence your expectation is incorrect. Using
global variables in an OOP framework is a bad idea anyway.

Categories