PHP封装没有类?
是否可以在 PHP 中封装变量或函数而不将它们包装在类中?我所做的是:
//Include the file containing the class which contains the variable or function
include('SomePage.php');
//Instantiate the class from "SomePage.php"
$NewObject = new SomeClassFromSomePage();
//Use the function or variable
echo $NewObject->SomeFuncFromSomeClass();
echo $NewObject->SomeVarFromSomeClass;
我的目的是避免命名冲突。这个例行公事虽然有效,但让我很累。如果我不能在没有类的情况下做到这一点,是否可以不实例化类?然后立即使用变量或函数?
Is it possible to encapsulate, a variable or function let say, in PHP without wrapping them in a class? What I was doing is:
//Include the file containing the class which contains the variable or function
include('SomePage.php');
//Instantiate the class from "SomePage.php"
$NewObject = new SomeClassFromSomePage();
//Use the function or variable
echo $NewObject->SomeFuncFromSomeClass();
echo $NewObject->SomeVarFromSomeClass;
My intention is to avoid naming conflict. This routine, although it works, makes me tired. If I cannot do it without class, it is possible not to instantiate a class? and just use the variable or function instantly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
PHP 命名空间 的目的是归档完全相同的目标:
当使用像这样调用命名空间函数:
PHP Namespaces were made to archive the exact same goal:
When using call namespaced functions like this:
这是一种无需类封装的方法
封装替代方案
使用此方法,您可以最大限度地减少无意使用数组键(使用它而不是变量)。分配后还可以在任何地方使用存储在数组中的值。数组键区长度较短,键内可变,封装函数内部;在封装函数之外,变量可以在键中使用,但也可以在长描述性键中使用。也可以使用嵌套封装。
例子
This is a way to encapsulate without Class
Encapsulation Alternative
With this method you can minimize unintentional using array key(uses it instead of variables). Can also use value stored in array anywhere after assigning. Shorter array key area length with variable in keys, inside encapsulation function; outside encapsulation function, variables can be used in keys but otherwise long discriptive keys. Nested encapsulation can also be used.
Example
要使用类方法和变量而不实例化,必须将它们声明为
静态
:在 PHP 5.3 中,您还可以使用 命名空间
To use class methods and variables without instantiating, they must be declared
static
:With PHP 5.3, you can also use namespaces