1

I am trying PHP to firebase insertion but I have got this error.

Fatal error: Uncaught Error: Call to a member function getReference() on null in C:\xampp\htdocs\makatravel1\Account.php:44 Stack trace: #0 C:\xampp\htdocs\makatravel1\Account.php(72): Account->insert(Array) #1 {main} thrown in C:\xampp\htdocs\makatravel1\Account.php on line 44

This is the code that I am trying to run-

class Account{
    protected $database;
    protected $dbname = "users";

    public function __construct(){
        $acc = ServiceAccount::fromJsonFile(__DIR__.'./firebase/key/makatravel2019-34ec2f4b7a9c.json');

        $firebase = (new Factory)
            ->withServiceAccount($acc)
            ->create();

        $database = $firebase->getDatabase();
    }

    public function insert(array $data){
        if(empty($data) || !isset($data)){
            return FALSE;
        }

        foreach($data as $key => $value) {
            $this->database->getReference()->getChild($this->dbname)->getChild($key)->set($value);
        }

        return TRUE;
    }
}



$users = new Account();

var_dump($users ->insert([
    '1' => 'John',
    '2' => 'Doe'
]));

1 Answer 1

1

Well, the error tells you that there is a problem with getReference() on null. You have one getReference() call in your code:

$this->database->getReference()->getChild($this->dbname)->getChild($key)->set($value);

The error states that there is a problem with $this->database, it is 'undefined' (null). However, you clearly defined it at the top of your class:

protected $database;

Then you try to set this variable in your constructor method:

$database = $firebase->getDatabase();

However, this is not how you should "address" the variable. You should use $this like you did with the call that results in the error:

$this->database = $firebase->getDatabase();

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.