phpconstructor

PHP calling model function


I'm trying to learn constructors and statics and I'm not sure what I'm doing wrong here

controller

<?php

namespace App\Http\Controllers\Api;
use App\Models\SampleModel;

class SampleController
{
    private static $sm;
    
    public function __construct() {
        self::$sm = new SampleModel;
    }
    
    // called via ($class)::{$function}($params);
    public static function create($file_id)
    {
        self::$sm->createRecord($file_id); // error occurs when this line is triggered
    }
}

model

<?php

class SampleModel
{
    public function createRecord($file_id)
    {
        return true;
    }
}

error

local.ERROR: Call to a member function createRecord() on null

Solution

  • You're calling a static method create() that uses a property initialized in the constructor. But constructors are not called when using a class statically, so self::$sm is null.

    Use instance methods instead of static methods, so the constructor runs and $this->sm is available.

    $controller = new SampleController();
    $controller->create($file_id);
    

    And change create() to:

    public function create($file_id)
    {
        $this->sm->createRecord($file_id);
    }
    

    PHP instance methods (use $this): https://www.php.net/manual/en/language.oop5.basic.php#language.oop5.basic.class.members