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;
?>
$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.
The syntax of making an object in php is
$obj=new class();
You have missed () after class name.
I think it should be
$database = new database();
instead of
$database = new database;
精彩评论