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 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染