PHP OOP - I am trying to output an array which has been loaded into a different class
class_1.php
class class_1
{
public function __construct()
{
require_once $_SERVER['DOCUMENT_ROOT'].'/array.php';
}
}
class_2.php
class class_2
{
static function output_array()
{
return $array_NUMBERS;
}
}
array.php
$array_NUMBERS = array('1', '2', '3');
page.php
require_once $_SERVER['DOCUMENT_ROOT'].'/class_1.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/class_2.php';
$obj = new class_1();
$numbers = class_2::output_array();
echo '<pre>';
print_r($numbers);
What am I doing wrong here? Aren't you supposed to use "require_once" within classes?
Problem: It's not outputting the array val开发者_如何学Goues.
You're creating a local variable in class_1::__construct()
, which falls out of scope immediately and is lost forever.
Even if it weren't, variables declared inside a function are local to that function, and cannot be access from other functions. class_2::output_array()
has no concept of the variable $array_NUMBERS
. You need to read up on scope.
To make this work, you'd have to make the variable a public member of class_1
:
class class_1 {
public $array_NUMBERS;
function __construct() {
require_once('array.php');
}
}
class class_2 {
public static function output_array() {
$class1 = new class_1();
return $class1->array_NUMBERS;
}
}
array.php:
$this->array_NUMBERS = array(...);
Think of it this way: include()
and co. are for pulling code in at a certain place, essentially what's happening in class_1.php
is that you're ending up with the equivalent of this:
class class_1
{
public function __construct()
{
$array_NUMBERS = array('1', '2', '3');
}
}
Thus, $array_NUMBERS
is a local variable within the constructor, which is why class_2
can't see it.
With your require_once
your code becomes:
class class_1
{
public function __construct()
{
$array_NUMBERS = array('1', '2', '3');
}
}
So what you are doing, is assigning a variable in a function. As a result, the scope of that variable is only inside that function.
There are ugly hacks to get the variable to your other class / function, but the whole approach seems wrong (also see @Mike Lewis's answer).
A solution would be to define a variable in class_1
, assign the array to that variable and pass the instance of that class as an argument to your output_array
function.
精彩评论