实例化PHP类的更好方法

实例化PHP类的更好方法,php,Php,我有一个只有一个函数的类: <?php class EventLog { public function logEvent($data, $object, $operation, $id) { //Log it to a file... $currentTime = new DateTime(); $time = $currentTime->format('Y-m-d H:i:s'); $logFi

我有一个只有一个函数的类:

<?php

class EventLog
{

    public function logEvent($data, $object, $operation, $id)
    {
        //Log it to a file...
        $currentTime = new DateTime();
        $time = $currentTime->format('Y-m-d H:i:s');

        $logFile = "/.../event_log.txt";
        $message = "Hello world";

        //Send the data to a file...
        file_put_contents($logFile, $message, FILE_APPEND);
    }

}

问题是:我在每个函数中都使用了上述代码,我想知道的是,是否有一种方法可以为所有需要它的函数实例化EventLog类一次

您可以在脚本的开头(例如)创建单个实例,并将其注入需要它的类的构造函数中。这称为依赖注入。大多数PHPWeb框架都利用这一原理

class Logger
{
   public function writeToLogFile(){
   ...
   }
}


class DoSomethingUseful
{
     private $logger;
     public function __construct(Logger $logger) //php 7 optional type hinting
     {
          $this->logger = $logger;
     }

     public function actualWork()
     {
          //do work
          $this->logger->writeToLogFile('whatever');
     }
}

class Application
{
     public function setUp()
     {
         //create database connection, other stuff
         $this->logger = new Logger;
     }

     public function work()
     {
         $action = new DoSomethingUseful($this->logger);
         $action->actualWork();

     }
}

您还可以尝试使用PHP Trait(使用名称空间):


检查这一个,使用依赖项注入并将
事件日志
绑定为一个单例,或者使该方法成为静态的。谢谢,我看了一下,但它说“在PHP中不是很有用”。他能不能简单地创建一个
公共$log
,并在他的类的构造函数中简单地d
$log=new EventLog()-方法
logEvent
也应该在其他类的每个方法中都可用,否则我错了?“但它说‘在PHP中不是很有用’”-静态方法在PHP中肯定有用。它们也可能被滥用。在你的例子中,我会选择依赖注入。这可能是因为我需要实例化的类扩展了实现另一个类的另一个类吗?例如,我需要调用EventLog类的类定义如下:类参与方扩展组件实现ValidatableParse错误:语法错误,意外的“$log”(T_变量),在/home/…中需要函数(T_函数)./…这是我实例化它的方式:类myClass扩展组件实现Validate{$log=new EventLog();公共函数add(){$log->logEvent(param1,param2,param3,param4);}}}我相信你的语法错误是因为你在类名声明之后有一行“$log=new EventLog();”,而不是在函数内部。这很有效。谢谢你,伙计!!不过我确实将代码改编为PHP5.6。干杯!!
class Logger
{
   public function writeToLogFile(){
   ...
   }
}


class DoSomethingUseful
{
     private $logger;
     public function __construct(Logger $logger) //php 7 optional type hinting
     {
          $this->logger = $logger;
     }

     public function actualWork()
     {
          //do work
          $this->logger->writeToLogFile('whatever');
     }
}

class Application
{
     public function setUp()
     {
         //create database connection, other stuff
         $this->logger = new Logger;
     }

     public function work()
     {
         $action = new DoSomethingUseful($this->logger);
         $action->actualWork();

     }
}
<?php
namespace App\Traits;

trait EventLog
{

    public function logEvent($data, $object, $operation, $id)
    {
        //Log it to a file...
        $currentTime = new DateTime();
        $time = $currentTime->format('Y-m-d H:i:s');

        $logFile = "/.../event_log.txt";
        $message = "Hello world";

        //Send the data to a file...
        file_put_contents($logFile, $message, FILE_APPEND);
    }

}
<?php
namespace App;

// import your trait here
use App\Traits\EventLog;

class OtherClass
{
    use EventLog;

    public function sample() {
        // sample call to log event
        $this->logEvent($data, $object, $operation, $id);
    }

}