PHP 中类的 var
我正在使用 PHP 类进行登录。 登录过程检查用户的 MySQL 数据库定义如下:
class flexibleAccess{
var $dbName = 'mydatabase';
但是,当我为不同的人安装应用程序时,这个 $dbName 需要不断更改。 我决定创建一个配置文件来保存数据库信息,这样我就必须在那里进行更改,因为这个登录类“隐藏”在某个地方,所以更容易。 问题是我想做这样的事情:
class flexibleAccess{
var $dbName = $_SESSION['mydatabase'];
我收到错误:“解析错误:第 43 行 path/access.class.php 中的解析错误” 第 43 行是 $dbName 行...为什么我不能使用它从会话中动态获取我的值? 我应该如何使用它?
谢谢
I am using a PHP class for login purposes. The MySQL database that the login process checks for the user is defined like this:
class flexibleAccess{
var $dbName = 'mydatabase';
However, as I install the application for different people, this $dbName needs constant changes. I have decided to make a config file where I keep my database information so I would have to change there witch is more easy as this login class is "hidden" somewhere. The problem is I want to do something like this:
class flexibleAccess{
var $dbName = $_SESSION['mydatabase'];
And I get the error: "Parse error: parse error in path/access.class.php on line 43"
The line 43 is the line with $dbName... Why can't I use this to dynamically get my values from the session ? And how should I use it ?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能不应该将数据库配置放在会话中。 对我来说感觉有点冒险。
我将使用这些信息创建一个配置文件,并将其包含在常量中:
dbconfig.php:
flexibleaccess.php:
任何需要数据库访问的文件:
当然,您不需要将其设置为常量。 关键是您将配置与代码放在单独的文件中。
You probably shouldn't put database configuration in the session. It feels a bit risky to me.
I would create a configuration file with the information and include it with a constant:
dbconfig.php:
flexibleaccess.php:
Any files that need database access:
Of course, you don't need ot set it as a constant. The key is that you're putting the configuration in a separate file from your code.
在 构造函数 中执行此操作(我在这里假设 php5 ...)
对于 php4,请将 __construct 替换为类的名称。
Do it in a constructor (I'm assuming php5 here...)
For php4, replace __construct with the name of the class instead.
您必须在类的构造函数中将此变量分配为 PHP 4 仅允许常量作为初始值设定项的值:
You have to assign this variable in the constructor of the class as PHP 4 only allows constant values as initializers:
或者,您可以在调用类时指定类应从何处读取此信息,例如:
这样您的类就保持干净,并且可以从您喜欢的任何源或方法接受数据库名称(以及可能不同的任何其他信息) 。 作为一个额外的好处,您不必注意您使用的是哪个版本的 PHP,它在这两个版本中都可以正常工作。
希望这可以帮助!
-戴夫
Alternatively you can specify where the class should read this information from while calling the class, for example:
This way your class stays clean, and it can accept the database name (and any other information that might vary) from any source or method you prefer. As an added bonus, you don't have to pay attention to which version of PHP you're using, it'll work fine in both.
Hope this helps!
-Dave