* 对不起,我现在正在学习英语,我的英语仍然不太好。请理解我的情况。
据我所知,Static 需要使用 Class::Function(params);
比如这个。
class Foo {
static function Bar($msg){
echo $msg;
}
}
XE(是韩国开发的CMS)中有一个文件.
(XE官方网站 : http://www.xpressengine.com/?l=en)
当然,这是真实文件的摘要
<?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 .= "'n" . $header;
}
}
这是此文件顶部的注释。
它具有双重方法结构,易于使用的方法,可以调用 作为 self::methodname(),以及使用静态对象调用的方法。
在此评论中,它可以使用 Class::Function(),我一直在 XE.
中使用但它并没有说明他们是如何制造的。我怎样才能喜欢它?
编辑1 :
该文件的名称是上下文.class.php并且包含在其他文件中。
<?php
require(_XE_PATH_ . 'classes/context/Context.class.php');
Context::addBodyHeader("Some Codes");
?>
在此评论中,它可以使用 Class::Function() 并且我一直在 氙气。但它并没有说明他们是如何制造的。我怎样才能喜欢它?
::
称为范围解析运算符。
他们制作如下:
class MyClass {
public static function saySomething() {
echo 'hello';
}
public function sayHello() {
echo 'hello';
}
public function helloSay() {
self::sayHello();
}
}
MyClass::saySomething();
MyClass::sayHello();
MyClass::helloSay();
它们都输出:hello
他们使用 self
,它不需要静态的,您可以将self::
与$this->
进行比较,只是self::
也适用于静态函数。
也许手册可以帮助你
不确定这是否是您要做的,但是您可以在php public static function methodName()
中声明"static",然后使用Class::Method()
调用该函数 您还可以查看此内容以获取有关静态的更多数据。
编辑:
这是来自 php.net:
伪变量$this在从以下位置调用方法时可用 在对象上下文中。$this是对调用对象的引用 (通常是方法所属的对象,但可能是另一个对象 对象,如果该方法是从 次要对象)。
所以基本上你可以这样做(调用类方法静态方式)。