dsafgdafgdf45345 2011-08-19 18:19
浏览 93
已采纳

PHP require()或include()并调用类变量?

I imagine this is fairly simple and one I should be able to get but I am having trouble with it. I can't seem to find an answer for this anywhere.

Consider the scenario: I have two files (we'll call them index.php and global.php). I am properly referencing the require_once() file.

Index.php:

<?php
require_once('./global.php');

$database = new database();
echo $database->dbname;
?>

Global.php:

<?php
class database {
public $dbname = 'jdoe';
}
?>

This does not output 'jdoe' on the index.php page. However...if I place the following into global.php, it works:

<?php
class database {
public $dbname = 'jdoe';
}

$database = new database();
echo $database->dbname;
?>
  • 写回答

3条回答 默认 最新

  • dongll0502 2011-08-19 18:26
    关注
    $database = new database();
    

    You forgot the parenthesis. Also, take a look at the php documentation for Classes and Objects if you need more information about using classes in php.

    Update:

    Reading up on PHP Class Properties I came across this little tid-bit:

    [Class member variables] must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

    I'm not 100% certain on this, but it seems like PHP is seeing your string assignment as "run-time information". Try assigning your variable in the constructor (its probably better practice anyway).

    class database {
        public $dbname;
        function __construct() {
            $this->dbname= 'jdoe';
        }
        // Rest of class
    }
    

    Hope that helps! And if anyone could verify my assumption that would be great.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿