简体   繁体   中英

“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.

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.

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....
        );
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM