dsxxqndv41105 2015-02-01 15:38
浏览 39
已采纳

如何在没有静态的情况下使用Class :: Function(params)

* Sorry, I am learning English now and my English is still not so good. Please understand my situation.

As far as I know, Static is required to use like Class::Function(params);
Like this one.

class Foo {
    static function Bar($msg){
        echo $msg;
    }
}

There is one file in XE(is CMS developed in Korea).
(XE Official Site : http://www.xpressengine.com/?l=en)

Of course, This is a summary of real file

<?php

/**
 * Manages Context such as request arguments/environment variables
 * It has dual method structure, easy-to use methods which can be called as self::methodname(),and methods called with static object.
 */

class Context
{
   /**
    * codes after <body>
    * @var string
    */
   public $body_header = NULL;

   /**
    * returns static context object (Singleton). It's to use Context without declaration of an object
    *
    * @return object Instance
    */
   function &getInstance()
   {
      static $theInstance = null;
      if(!$theInstance)
      {
         $theInstance = new Context();
      }
      return $theInstance;
   }

   /**
    * Add html code after <body>
    *
    * @param string $header Add html code after <body>
    */
   function addBodyHeader($header)
   {
      is_a($this, 'Context') ? $self = $this : $self = self::getInstance();
      $self->body_header .= "
" . $header;
   }
}

This is the comment at the top of this file.

It has dual method structure, easy-to use methods which can be called as self::methodname(),and methods called with static object.

In this comment, It can use Class::Function() and I have been using in XE.
But it don't tell how they make. How can I make like it?

Edit1 :

The file's name is Context.class.php and It is included in other files.

<?php
    require(_XE_PATH_ . 'classes/context/Context.class.php');
    Context::addBodyHeader("Some Codes");
?>
  • 写回答

3条回答 默认 最新

  • douyingtai6662 2015-02-01 16:41
    关注

    In this comment, It can use Class::Function() and I have been using in XE. But it don't tell how they make. How can I make like it? The :: is called the scope resolution operator.

    They make it as follows:

    class MyClass {
        public static function saySomething() {
            echo 'hello';
        }
         public function sayHello() {
            echo 'hello';
        }
    
        public function helloSay() {
            self::sayHello();
        }
    }
    

    MyClass::saySomething();

    MyClass::sayHello();

    MyClass::helloSay();

    They all output: hello

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 qgcomp混合物线性模型分析的代码出现错误:Model aliasing occurred
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥15 小红薯封设备能解决的来
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答