Page 1 of 1

__set before __construct

Posted: Mon Feb 19, 2007 6:34 am
by AshrakTheWhite
hey, my problem is im trying to use __set before i run __construct, any way to do that??

the code:

Code: Select all

<?php
require_once('html_printer.php');

$data = array('1', '2', '3');
$printer = new html_printer();
$printer->data = $data;


?>

Code: Select all

<?php
class html_printer
{
	private $data = array();

	public function __set($variable, $value)
	{
		$this->$variable = $value;
	}
	
	public function __construct()
	{		
		//make head and css
		$this->header();
		
		//printout the entire crap for the report
		$this->body();
		
		//printout closing tags
		$this->footer();
	}


	private function header ()
	{
		$this->css();
		print_r($this);
	}

	private function body ()
	{
		
	}

	private function footer ()
	{
		
	}

	private function css ()
	{

	}
}
?>

cheers

Posted: Mon Feb 19, 2007 6:53 am
by Jenk
__construct() is invoked when you initialise/instantiate the object, so it will run before anything else is run in your object.

Code: Select all

$var = new Object; // this is calling the __construct() method.

Posted: Mon Feb 19, 2007 7:11 am
by AshrakTheWhite
any other way of giving the data variable a value short of doing the stuff i do in __set inside of __construct?

Posted: Mon Feb 19, 2007 7:54 am
by feyd
The only way to give variables data in an class/object before an instance is available is through the use of static properties. I wouldn't recommend it however. I would say your logic needs rethinking if this is actually needed.

Posted: Mon Feb 19, 2007 9:17 am
by Chris Corbyn

Code: Select all

$data = array('1', '2', '3');
$printer = new html_printer($data);
//

class html_printer
{
    // ... snip ...
    
    public function __construct(array $data)
    {
        $this->data = $data;
    }
    
    // ... snip ....
    
}

Posted: Mon Feb 19, 2007 10:13 am
by AshrakTheWhite
i killed construct all together and just call it from test.php