如何将公共方法称为静态?

时间:2016-02-16 14:39:30

标签: php

我想使用自己的库来跟踪系统中发生的所有活动。现在,不是在每个系统文件中包含此库,而是创建一个文件并包含名为trace的库。让我举个例子:

<?php

    class Trace
    {
         public function __construct()
         {
             //Some stuff.
         }

         public function info()
         {
           // write an info text on the log txt file.
         }

    }

上面的代码基本上解释了trace库在系统中的作用,主要是在txt文件上写一些东西。无论如何,我想创建一个单独的类,将Trace的所有方法扩展为静态,所以我可以在扩展它的文件中调用trace的方法(对不起周围的单词),例如:

<?php

      include "trace.php";

      class Test 
      {

      private $_trace;

      public function __construct()
      {
           //Create a new instance here?
           $this->_trace = new Trace();
      }

      public static function info()
      {
          $this->_trace->info() //I can't call $this in static method, this is the main problem
      }
      } //end class

如何看待我无法做到这一点&#39;因为$this方法无法调用static,我该怎么办呢?

1 个答案:

答案 0 :(得分:2)

如果我理解正确,你想要一个拥有Trace实例的类,并且会有静态方法。顺便说一句,你的班级不是单身人士。

方法1:使用静态方法

<?php

  include "trace.php";

  class Test 
  {

      private static $_trace;

      public static function info()
      {
          self::getTraceInstance()->info();
      }

      private static getTraceInstance()
      {
          if (!isset(self::$trace)) {
              self::$trace = new Trace();
          }
          return self::$trace;
      }
  } 

  // usage:
  $test = new Test();
  $test->info();

方法2:使Test类成为Singleton

<?php

  include "trace.php";

  class Test 
  {

      private static $_instance;

      private $_trace;

      private function __construct()
      {
          $this->_trace = new Trace();
      }    

      public static function getInstance()
      {
          if (!isset(self::$_instance)) {
              self::$_instance = new static;
          }
          return self::$_instance;
      }   

      public function info()
      {
          $this->_trace->info();
      }          
  } 

  // usage:
  Test::getInstance()->info();