简体   繁体   中英

PHP require() or include() and call a class variable?

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;
?>

The syntax of making an object in php is

$obj=new class();

You have missed () after class name.

$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.

I think it should be

$database = new database(); 

instead of

$database = new database;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM