Strange error in class method call

Asked

Viewed 22 times

1

I have a simple class with 2 methods, here is the code:

namespace app\Services;


use App\Repositories\LogRepository;

class LogService
{

    protected $repository;


    public function __construct(LogRepository $repository){
        $this->repository=$repository;
    }

    public function cadastrar($dados){
        return 'ola2';
    }

    public function deletar($id=0)
    {
        return 'ola';
    }
}

And in another class I call this class:

namespace app\Classes;

use App\Repositories\LogRepository;
use app\Services\LogService;

class Log
{
    private static $repository;

    private static $service;

    public function __construct(LogRepository $repository, LogService $service)
    {
        self::$repository=$repository;
        self::$service=$service;
    }

    static function Gravar($tabela, $evento, $sql=null, $valoresAntigos, $valoresNovos){
        self::$service->deletar(1);

        return true;
    }
}

When I run me the following error:

Fatalerrorexception in Log.php line 29: Call to a Member Function deletar() on null

What am I forgetting to do or doing wrong? Thank you

  • I think: you create an instance of $service in your Log class constructor. But the Save function is static. Therefore, the constructor is not executed. It’s just a kick, I’ve never used PHP.

  • Can you make this right? Because I need this static class.

  • To test try creating the instance in the write function itself.

1 answer

1

Your error is in trying to execute a property that does not exist null.

Static methods nay execute the constructor method of the class, as nothing is instantiated. See that example:

<?php

class teste{

    public function __construct(){

        echo "executando construtor\n";
    }

    public static function ola(){
        echo "Metodo estático\n";
    }

}

teste::ola();

The result will simply be:

Static method

I advise you not to create static methods if you do not understand your concepts very well and how to use it correctly.

To use your class Log create an instance of it is simpler:

namespace app\Classes;

use App\Repositories\LogRepository;
use app\Services\LogService;

class Log
{
    private $repository;

    private $service;

    public function __construct(LogRepository $repository, LogService $service)
    {
        $this->repository=$repository;
        $this->service=$service;
    }

    public function Gravar($tabela, $evento, $sql=null, $valoresAntigos, $valoresNovos){
        $this->service->deletar(1);

        return true;
    }
}

// Uso
$repository = new App\Repositories\LogRepository;
$service = new app\Services\LogService\LogService;

// Insere as dependências
$log = new Log($repository, $service);

$log->gravar(...);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.