是否可以在PHP中创建静态类(如C#中)? [英] Is it possible to create static classes in PHP (like in C#)?
本文介绍了是否可以在PHP中创建静态类(如C#中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
- 构造函数被自动调用对课程的第一次电话
- 不需要实例化
这样的东西...
static class Hello {
private static $ greeting ='Hello'
private __construct(){
$ greeting。='There!';
}
public static greet(){
echo $ greeting;
}
}
Hello :: greet(); // 你好!
解决方案
您可以在PHP中安装静态类, t自动调用构造函数(如果您尝试调用 self :: __ construct()
,您将收到错误。)
因此,您必须创建一个 initialize()
函数并在每个方法中调用它:
<?php
class Hello
{
private static $ greeting ='Hello';
private static $ initialized = false;
private static function initialize()
{
if(self :: $ initialized)
return;
self :: $ greeting。='There!';
self :: $ initialized = true;
}
public static function greet()
{
self :: initialize();
echo self :: $ greeting;
}
}
Hello :: greet(); // 你好!
?>
I want to create a static class in PHP and have it behave like it does in C#, so
- Constructor is automatically called on the first call to the class
- No instantiation required
Something of this sort...
static class Hello {
private static $greeting = 'Hello';
private __construct() {
$greeting .= ' There!';
}
public static greet(){
echo $greeting;
}
}
Hello::greet(); // Hello There!
解决方案
You can have static classes in PHP but they don't call the constructor automatically (if you try and call self::__construct()
you'll get an error).
Therefore you'd have to create an initialize()
function and call it in each method:
<?php
class Hello
{
private static $greeting = 'Hello';
private static $initialized = false;
private static function initialize()
{
if (self::$initialized)
return;
self::$greeting .= ' There!';
self::$initialized = true;
}
public static function greet()
{
self::initialize();
echo self::$greeting;
}
}
Hello::greet(); // Hello There!
?>
这篇关于是否可以在PHP中创建静态类(如C#中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文