1

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.

3
  • What is the question/problem/error? Commented Mar 17, 2011 at 22:32
  • Please edit the post to include your error message, if any, or how your program functions differently than your expectations. We are not mind readers. Commented Mar 17, 2011 at 22:33
  • It's not outputting the array values. Just a blank page. Commented Mar 17, 2011 at 22:33

3 Answers 3

3

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(...);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.