How To Ideas | How To Articles | How To Tutorials


0

How to Declare Dynamic Function/Constructor in php


In many cases you wanted to declare dynamic function which allows you to pass multiple parameters. Here is the example to demonstrate the dynamic function or constructor. Take an example of database connection class in which you want to pass 3 or 4 parameters to constructor.

<?php
class db_connection{

//To store the databse name
private $_database = "";

//To store the connection values
private $_mysqli_link;

//Declaration of dynamic constructor
public function __construct(){
//If number of arguments are 3
// Host + Username + Password
if(func_num_args() == 3) {
$this->_mysqli_link = mysqli_connect(func_get_arg(0),func_get_arg(1),func_get_arg(2)) or die("Database connection failed.<br/>");
}

//If number of arguments are 4
// Host + Username + Password + Database Name
elseif(func_num_args() == 4) {
$this->_database = func_get_arg(3);
$this->_mysqli_link = mysqli_connect(func_get_arg(0),func_get_arg(1),func_get_arg(2),func_get_arg(3)) or die("Database connection failed.<br/>");
}

// If any other syntax is used to instantiate the class
else {
die("Connection declaration syntax is invalid");
}
}

// Function to select or change the database name
public function db_select($database){
mysqli_select_db( $this->_mysqli_link,$database ) or die("Database selection failed.");
$this->_database = $database;
}
}
?>

You can download the source code of this example here.

Enjoy

Incoming search terms:

  • php dynamic functions (1)
Filed in: PHP Tags: , , , , , , , , ,

Leave a Reply

Submit Comment



© 2012 How To Ideas. All rights reserved.
Proudly designed by Theme Junkie.