FireForce
FireForce

Reputation: 23

PHP object is null after initialization

I have the class file:

class Settings
{
public $siteName;
public $siteAddr;
public $dbUrl;
public $dbName;
public $dbPass;

public function __construct()
{
$siteName = 'Welcome';
$siteAddr = 'http://site.com';
$dbUrl = 'test';
$dbName = 'base';
$dbPass = '123';
}
}

Trying to use it in other file:

require_once('settings.php');
$cfg = new Settings();
var_dump($cfg); // <--- everywhere is null...

Why does it contain only nulls?

Upvotes: 0

Views: 123

Answers (2)

lafor
lafor

Reputation: 12776

The variables you're using in your constructor are local scope variables. To refer to class fields use $this->fieldname.

Upvotes: 0

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

Instead of

$siteName = 'Welcome';

you need

$this->siteName = 'Welcome';

otherwise you just created variables in scope of your constructor, not initialized object members.

Upvotes: 3

Related Questions