Strange error in class method call

1

Personal 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 it gives me the following error:

  

FatalErrorException in Log.php line 29:   Call a member function delete () on null

What am I forgetting to do or doing wrong? Thanks

    
asked by anonymous 31.07.2015 / 14:24

1 answer

1

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

Static methods do not execute the constructor method of the class because nothing is instantiated. See this 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 them 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(...);
    
31.07.2015 / 14:47