954,604 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

need helps about php constructor

hi all..
I just want to ask,is it correct,in a class that we have built,PHP will first execute the constructor function before the others??

to make it clear is this is example :

<?php
class database {
	
	public function __construct() {
		$this->open_connection();
        }

	
	public $connection;
			
	public function open_connection() {
	   $this->connection= mysql_connect("localhost","root","mypassword");
	if(!$this->connection) {
		die ("connetion failed: " . mysql_error());
          } 	
	
        public function close_connection() {
	  $connection=mysql_close($this->connection);
         }

}


$database=new database(); 
?>


is it because of the PHP will execute the constructor function first,then i cannot write this code ? :

public function __construct () {
    $this->$sonnection;
 }

please help..
Thank You :)

samsons17
Posting Whiz in Training
233 posts since Oct 2009
Reputation Points: 6
Solved Threads: 1
 

The constructor is always executed first of all functions.
About your code, $this->$connection is invalid. You may want to use $this->connection.
But note, your connection must be active before using it anywhere in the class.

nileshgr
Junior Poster
166 posts since Aug 2009
Reputation Points: 17
Solved Threads: 23
 

If you dont want to execute the constructor then remove the constructor from the class.

rajarajan07
Nearly a Posting Virtuoso
1,447 posts since May 2008
Reputation Points: 167
Solved Threads: 239
 

Thanks :)

samsons17
Posting Whiz in Training
233 posts since Oct 2009
Reputation Points: 6
Solved Threads: 1
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You