Jump to content

Transformation from procedural to oo code.


piekarnik

Recommended Posts

Hi all,

I work on a php project. I wrote it in procedural way. As project grows, it stating be harder to maintain obviously and  I want to convert project ( or at lease key features) to oo code. 

My intention is to replace part which for example connects to database and then use the rest of the script and then move to another part write it in oo and replace old part.  I wrote a simple class called Connection, just to handle connection.  When I make object it connects,  I retrieve some info from database using query as class function. However,  there is no way I can execute my procedural login script after I made a connection object. And question is why? Do I need to write whole Database class to handle it? Can I merge oo and procedural php code together in once script?

Code sample:

class Connection{
// database access paramiters
var $host = 'localhost';
var $data_base = 'database';
var $user = 'user';
var $pass = 'pass';
var $con_handle;

// constructing object with automatic connetction to db
function __construct(){
	$this->connect();
}

function connect(){
	// open a connection to the database server
	$this->con_handle = new mysqli ($this->host,  $this->user, $this->pass);
	if (mysqli_connect_errno())	{
		echo("Could not open connection to database server");
		exit;
	}
	// selecting database
	$this->con_handle->select_db($this->data_base) or die(mysql_error());
}
}

//{ few includes here}
$connection= new Connection();
//{rest of my login script}

Link to comment
Share on other sites

Firstly, you cannot convert procedural code to OOP, the design principles are entirely different. You will just end up with procedural code wrapped in OO syntax.

 

Now, your issue: A __construct returns an instance of an object, in this case your Connection object. Your Connection object in turn doesn't have any means to expose an actual connection. You would actually need to return $this->con_handle from your connect() method then use it something like....

 

$connection= new Connection();
$actualconnection = $connection->connect();

Link to comment
Share on other sites

  • 2 weeks later...
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.