I was wondering if you could overload functions in PHP, specifically in CodeIgniter. For instance in my Controller if I were to load a view, but it would differ whether a variable was supplied as a parameter or if it was left blank. This is the concept I tried, which is how I learned in other languages:
<?php
function load_view(){
$this->load->view('view');
}
function load_view($var){
$this->load->model('data');
$data = $this->data->getInfo($var);
$this->load->view('view', $data);
}
?>
But when I tried this, I get an error "Fatal error: Cannot redeclare Controller::load_view"...
Any help would be greatly appreciated. Thanks in advance!
An overloaded function is really just a set of different functions that happen to have the same name. The determination of which function to use for a particular call is resolved at compile time. In Java, function overloading is also known as compile-time polymorphism and static polymorphism.
Function overloading and overriding is the OOPs feature in PHP. In function overloading, more than one function can have same method signature but different number of arguments. But in case of function overriding, more than one functions will have same method signature and number of arguments.
Function overloading in PHP is used to dynamically create properties and methods. These dynamic entities are processed by magic methods which can be used in a class for various action types. Function overloading contains same function name and that function performs different task according to number of arguments.
In Java, two or more methods may have the same name if they differ in parameters (different number of parameters, different types of parameters, or both). These methods are called overloaded methods and this feature is called method overloading. For example: void func() { ... }
In PHP to overload functions use optional parameters. An example might be:
function load_view($var = null) {
if (!empty($var)) {
$this->load->model('data');
$data = $this->data->getInfo($var);
$this->load->view('view', $data);
} else {
$this->load->view('view');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With