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 values.
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:array.php: