PHP: Use outside variable in static function in class - php

I would like to use a values stored in a seperate file in a static function in a PHP class.
Example:
<?php
include "vars.php";
class MyClass {
public static function doSomething() {
echo "Default value is ".$default_value;
}
}
MyClass::doSomething();
?>
And in vars.php
<?php
$default_value = "DEFAULT";
?>
I get following error:
Notice: Undefined variable: default_value in C:\xampp\htdocs\mediamanager\new_hp\MyClass.php on line 6
Default value is
How would this be possible? Or is there a better way to read configuration values from a seperate file?

You could declare $default as a global variable using the global keyword, or put it into the GLOBALS superglobal.
Ps: For configuration, I would personally use a class, with constant members.

Related

Accessing variable inside function - php [duplicate]

This question already has answers here:
Can't access global variable inside function
(5 answers)
Closed 9 years ago.
i need to access a variable which is declared in another php file within a function.. How can i do it?
a.php
<?php
$global['words']=array("one","two","three");
echo "welcome"
?>
b.php
<?php
$words = $global['words'];
require_once('a.php');
print_r($global['words']);
function fun()
{
print_r($global['words']); // not displaying here
}
fun();
?>
now i am able to access the "$global['words']" variable in b.php file, but not within function, how can i make it visible inside the function?
The preferred option is to pass as a parameter:
function fun($local) {
print_r($local['words']);
}
fun($global);
If for some reason you can't use that approach, then you can declare the variable as global:
function fun() {
global $global;
print_r($global['words']);
}
fun();
Or use the $GLOBALS array:
function fun() {
print_r($GLOBALS['global']['words']);
}
fun();
But in general, using global variables is considered bad practise.
actually your function does n't know about anything outside it, if it's not a classes, or global php vars such as $_POST , you can try to define function as:
function fun() use ($globals)
{
}

Using $GLOBALS[] variable in PHP class function

I'm trying to assign $GLOBALS['a'] variable in function from class, but haven't succeeded.
Here is my code:
<?php
$GLOBALS['a'] = "alter";
class db_data
{
public $a;
function __construct()
{
$this->a = $GLOBALS['a'];
}
}
$db = new db_data;
echo $db->$a;
?>
And produced this error:
Notice: Undefined property: db_data::$alter.....
I tried to search on SO for this, but all questions were different and it did not resolve my problem.
Answers are in the question comments, but here's why it's happening
You're accidentally using the variable variables feature of PHP. When you call $thing->$a, you're actually getting the value of $a (which defined by the $GLOBALS['a'] = "alter"; line), and then getting the property of $thing with that value.
As stated in your comments, you should simply echo $db->a, as that's how PHP properties are accessed
Also, Watch out!, if the value of $a is changed elsewhere in the global scope, your db_data class will reflect that change, which you probably don't want.

How to access constant variables (defined in another file) dynamically in a function?

I have a file that defines constant variables, like this:
define_vars.php
<?
define("something","value");
define("something1","value");
define("something2","value");
define("something3","value");
And I have a function which parses $var as the constant variable name, like this:
function something($var=''){
include('define_vars.php');
// $var is the name of one of the variables I am defining in the other file (define_vars.php)
// So $var may have a value of "something3", which is the name of one of the constants defined in the other file...
}
I need to somehow get the value of the constant, when $var holds the name of the constant I wish to get the value of....make sense? :S
Any Ideas?
http://php.net/constant
function something($var) {
if (defined($var)) {
$value = constant($var);
}
}
Also you should make sure that the file with the definitions gets included only once, so use require_once('define_vars.php'); instead.
You want constant()
constant($var); // value
Use constant() to get the value. You could do something like this
function something($var = '') {
include_once('define_vars.php'); //you don't want to include the file more than once or it will cause a fatal error when trying to redefine your constants
return (defined($var) ? constant($var) : null);
}

I have a require("config.php") with arrays, but still get Undefined variable error

I hava a function that looks something like this:
require("config.php");
function displayGta()
{
(... lots of code...)
$car = $car_park[3];
}
and a config.php that look something like this:
<?php
$car_park = array ("Mercedes 540 K.", "Chevrolet Coupe.", "Chrysler Imperial.", "Ford Model T.", "Hudson Super.", "Packard Sedan.", "Pontiac Landau.", "Duryea.");
(...)
?>
Why do I get Notice: Undefined variable: car_park ?
Try adding
global $car_park;
in your function. When you include the definition of $car_park, it is creating a global variable, and to access that from within a function, you must declare it as global, or access it through the $GLOBALS superglobal.
See the manual page on variable scope for more information.
Even though Paul describes what's going on I'll try to explain again.
When you create a variable it belongs to a particular scope. A scope is an area where a variable can be used.
For instance if I was to do this
$some_var = 1;
function some_fun()
{
echo $some_var;
}
the variable is not allowed within the function because it was not created inside the function. For it to work inside a function you must use the global keyword so the below example would work
$some_var = 1;
function some_fun()
{
global $some_var; //Call the variable into the function scope!
echo $some_var;
}
This is vice versa so you can't do the following
function init()
{
$some_var = true;
}
init();
if($some_var) // this is not defined.
{
}
There are a few ways around this but the simplest one of all is using $GLOBALS array which is allowed anywhere within the script as they're special variables.
So
$GLOBALS['config'] = array(
'Some Car' => 22
);
function do_something()
{
echo $GLOBALS['config']['some Car']; //works
}
Also make sure your server has Register globals turned off in your INI for security.
http://www.php.net/manual/en/security.globals.php
You could try to proxy it into your function, like:
function foo($bar){
(code)
$car = $bar[3];
(code)
}
Then when you call it:
echo foo($bar);
I had the same issue and have been tearing my hair out over it - nothing worked, absolutely nothing - until in desperation I just copied the contents of config.php into a new file and saved it as config2.php (without changing anything in its contents at all), changed the require_once('config.php'); to require_once('config2.php'); and it just started working.

if i define something in a class, how do i call in within the class?

i have something like
define("__ROOT_PATH__", "http://{$_SERVER['HTTP_HOST']}/admin");
within a class. how do i call it from within functions is it with a cologn? i tried looking it up on google but nothing.
thanks
The function define() is intended for global constants, so you just use the string __ROOT_PATH__ (I would recommend using another naming scheme, though. Constants starting with two underscores are reserved by PHP for their magic constants)
define('__ROOT_PATH__', 'Constant String');
echo __ROOT_PATH__;
If you want to declare a class constant, use the const keyword:
class Test {
const ROOT_PATH = 'Constant string';
}
echo Test::ROOT_PATH;
There is one problem though: The class constants are evaluated while your script is being parsed, so you cannot use other variables within these constants (so your example will not work). Using define() works, as it is treated like any other function and the constant value can be defined dynamically.
EDIT:
As PCheese pointed out, you can access class constants using the keyword self, instead of the class name from within the class:
class Test {
const ROOT_PATH = 'Constant string';
public function foo() {
echo self::ROOT_PATH;
}
}
# You must use the class' name outside its scope:
echo Test::ROOT_PATH;
Using define will define the constant globally, so just refer to it directly in your code:
echo __ROOT_PATH__;
If you want to scope a constant to a class, you need to declare it differently. However, this syntax will not let you declare it dynamically as you did above, using $_SERVER.
<?php
class MyClass {
const MY_CONST = "foo";
public function showConstant() {
echo self::MY_CONST;
}
}
// Example:
echo MyClass::MY_CONST;
$c = new MyClass();
$c->showConstant();
Simply use the name of the constant.
i.e.
echo "Root path is " . __ROOT_PATH__;

Categories