How to Add Parameters to Your PHP Class (Constructor Tutorial)
Constructors can be used for a variety of reasons. In my case, I needed it to connect to a database. Instead of using a function and a class, I combined my function into a constructor. For this reason, I will show you how to use a class to connect to a database as an example.
Step 1: Create the __construct() function in your class
I named my class icdb. You can, however, name it anything you want.
class icdb { function __construct() { } }
Step 2: Add parameters to the __construct() function
Add parameters to this like any other function.
function __construct($db_host, $db_user, $db_pass, $db_name) { }
Step 3: Make your function
Do whatever you want. Here I am connecting to a database, obviously.
function __construct($db_host, $db_user, $db_pass, $db_name) { global $db_prefix; $link = mysql_connect($db_host, $db_user, $db_pass); $db = mysql_select_db($db_name); $this->prefix = $db_prefix; return $link; }
Step 4: Add legacy support for PHP4
PHP 4 handles constructors differently. You must create a function with the name of your class within your class. Here, I must make the function icdb().
function icdb() { $this->__construct(); }
Final Code
You're now done! Here's all of the code put together.
class icdb { function icdb() { $this->__construct(); } function __construct($db_host, $db_user, $db_pass, $db_name) { global $db_prefix; $link = mysql_connect($db_host, $db_user, $db_pass); $db = mysql_select_db($db_name); $this->prefix = $db_prefix; return $link; } }
And to initialize the class:
$icdb = new icdb("localhost", "myUser", "myPass", "myDb");
And that's it! You are now connected to a database. Now all you need is to add functions to the class to work with the database!
You can use this method to add parameters to any PHP class.
This is my first tutorial, so please tell me if it doesn't make sense. :p
Thanks for reading my post! If you enjoyed it or it helped you, please consider liking/tweeting this page, commenting, or following me on GitHub or Twitter!