Jump to content

This class is killing me. Constructor runs, does not set values to variables.


Go to solution Solved by Jacques1,

Recommended Posts

Hello there :)

 

After a few years of spending less and less time coding, I've got a lot of catching up to do. Back when I left I usually would run without classes. Now this is a big deal for me today.

 

I do understand the concept of classes and already did some working models, mostly from my learning process.

 

Now here is what is bothering me:

<?PHP

class database {
	// Variables
	public $test;
	
	// Constructor
	public function __construct()
	{
		$test = "4";
	}
	
	
	// Functions
	//
	public function test()
	{
		var_dump($this->test);
	}
	
}

$test = new database;

$test->test();

?>

Wether I run this script on itself, nor through another file, this does work.

What i get is:

 

NULL

 

The constructor does run, I did an echo inside it. Also it does not matter if the variable is public, private or protected - it will be always NULL.

 

Error_reporting is on E_ALL, does not show any errors.

 

What have I overlooked?

  • Solution

$test is just a local variable. It's only available in the constructor itself and thrown away afterwards.

 

If you want to set the test attribute, you need to use

$this->test = "4";

Just like in your test() method.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.