PHP OOP 属性常量用法
我对 OOP 真的很陌生。我什至不是新手——我是菜鸟。所以。我想将我的伪 CMS 从“正常”编程转移到 OOP 编程系统中。那么:
private static $dsn = DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME;
这里是什么导致了问题?约束的使用?我不知道。我的编辑器(aptana studio)在 1 个常量后显示错误。谢谢
编辑:
感谢您的快速反应。我会在构造函数中完成它。
Edit2:
但是如果我想使用单例怎么办?如何将参数传递给构造函数?
I'm really new to OOP. I'm even not a newbie - I'm noob. So. I want to transfer my pseudo-CMS from "normal" programming, into OOP programming system. And so:
private static $dsn = DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME;
What here causes problem? Usage of constraints? I don't know. My editor (aptana studio) shows error after 1 constant. Thanks
Edit:
Thanks for fast reaction. I'll do it in contructor.
Edit2:
But what if i want to use singleton? How to pass arguments to contructor?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
所有变量声明必须是完全静态的。这意味着不使用常量、变量或其他可变项。
要制作任何不完全纯文本的内容,您应该使用构造函数。
All variable declarations must be completely static. This means not use of constants, variables, or other changeable items.
To make anything that is not completely plain text, you should use the constructor.
问题在于,当您将属性放入初始值设定项字段时,属性必须是内联常量。
你正在做的事情不会起作用,但是,例如,这会:
private static $dsn = 'mysql:host=localhost;dbname=mydb';
我知道,这很愚蠢,但是你甚至不能使用 PHP 常量。您必须以纯文本形式获取它。
解决方案是在类的构造函数中初始化
$dsn
,如下所示:The problem is that properties have to be inline constants when you put them in the initializer fields.
What you're doing won't work, but this, for example, would:
private static $dsn = 'mysql:host=localhost;dbname=mydb';
I know, it's stupid, but you can't even use PHP constants. You have to literally have it in plain text.
The solution to this is to initialize
$dsn
in the class's constructor, like this:请参阅文档:
定义类属性时不能连接字符串。
文档中的示例(为了完整性):
无论如何,当您切换到 OOP 时,您不应该使用常量。将这些值传递给类的构造函数:
See the documentation:
You cannot concatenate strings when defining class properties.
Example from the documentation (for completness):
As you switch to OOP anyway you should not use constants. Pass those values to the constructor of your class: