Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use external variable inside PHP class

Tags:

php

I'm very new to PHP classes so forgive me if the answer is really obvious. I'm trying to figure out how to use a variable defined outside of a class inside of a class. Here is a very crude example

$myVar = 'value';

class myClass {
  private $class_var = $myVar;
  //REST OF CLASS BELOW
}

I know the above doesn't work, but how can I use the external $myVar inside the class?

like image 910
B_Chesterfield Avatar asked Jun 13 '13 18:06

B_Chesterfield


People also ask

How do you call a variable outside class in PHP?

functions outside any class are global an can be called from anywhere. The same with variables.. just remember to use the global for the variables... <? php function abc() { } $foo = 'bar'; class SomeClass { public function tada(){ global $foo; abc(); echo 'foo and '.

How can use global variable inside class in PHP?

Accessing global variable inside function: The ways to access the global variable inside functions are: Using global keyword. Using array GLOBALS[var_name]: It stores all global variables in an array called $GLOBALS[var_name]. Var_name is the name of the variable.

Can class access global variables?

As shown below, global variables can be accessed by any class or method within a class by simply calling the variable's name. Global variables can also be accessed by multiple classes and methods at the same time.

How do you declare a variable outside the class?

Variable defined inside the class: If you want to use that variable even outside the class, you must declared that variable as a global. Then the variable can be accessed using its name inside and outside the class and not using the instance of the class.


1 Answers

Try this:

$myVar = 'value';

class myClass {
  private $class_var;

  public function __construct($myVar) {
    $this->class_var=$myVar;
  }

  //REST OF CLASS BELOW
}

When declaring the class, you will need to pass $myVar like so, $myClass = new myClass($myVar);.

like image 115
Dave Chen Avatar answered Oct 02 '22 20:10

Dave Chen