TPoy
TPoy

Reputation: 962

"Call to undefined function" error when calling member function from constructor

Well this is depressing, but probably some little oversight I imagine.

I have this PHP class:

class SearchModel
{
    private $searchOptions;

    public function __construct()
    {
        $this->searchOptions = populateSearchOptions();
    }

    public function getSearchOption()
    {
        return $this->searchOptions;
    }

    private function populateSearchOptions()
    {
        $this->searchOptions = array(
            // values....
        );
    }
}

When I instantiate this class, PHP returns:

Fatal error: Call to undefined function populateSearchOptions() in SearchModel.php ...

When changing:

$this->searchOptions = populateSearchOptions();

to:

$this->searchOptions = $this->populateSearchOptions();

the complaint is gone but the contents of $searchOptions is NULL.

So... if I call populateSearchOptions() this way from inside the constructor, instantiate the class and try to output the contents of the array:

$this->model = new SearchModel();
// Output contents of model->searchOptions

The output is NULL. But when I do (and not bother trying to call populateSearchOptions() from the constructor):

$this->model = new SearchModel();
$this->model->populateSearchOptions();
// Output contents of $this->model->searchOptions

It outputs the values assigned to $this->model->searchOptions as desired.

Anyone know what's going on here? I'd like to simply be able to call populateSearchOptions() from the SearchModel constructor.

Upvotes: 1

Views: 5835

Answers (2)

David Lin
David Lin

Reputation: 13353

Output contents of model->searchOptions is NULL

it is null because it is a private variable

try making the searchOptions public then it will be good:

class SearchModel
{
    public $searchOptions;

    public function __construct()
    {
        $this->searchOptions = $this->populateSearchOptions();
    }

    private function populateSearchOptions()
    {
        $this->searchOptions = array(
            // values....
        );
    }
}

Upvotes: 0

Bryan
Bryan

Reputation: 3494

Change the constructor from

public function __construct()
{
    $this->searchOptions = populateSearchOptions();
}

to

public function __construct()
{
    $this->populateSearchOptions();
}

1) always use $this in php to call non static class methods and variables

2)The result was null before because the populateSearchOptions function does not return a value so you were effectively setting a value to it in the function then setting it to null immediately after.

alternatively you can change the populateSearchOptions function to

private function populateSearchOptions()
{
    return array(
        // values....
    );
}

and do effectively the same thing.

Upvotes: 3

Related Questions