Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function Overloading in CodeIgniter

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!

like image 821
Nick Corin Avatar asked Jul 02 '12 22:07

Nick Corin


People also ask

What is function overloading?

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.

What is difference between function overloading and overriding in PHP?

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.

Can we use function overloading in PHP?

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.

What is method overloading example?

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() { ... }


1 Answers

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');
     }
}
like image 108
Doug Owings Avatar answered Nov 09 '22 04:11

Doug Owings