0

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?

2 Answers 2

3

Instead of

$siteName = 'Welcome';

you need

$this->siteName = 'Welcome';

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.