Naming method inside of a Class

Robert Granlund
Robert Granlund used Ask the Experts™
on
In MVC OOP  I am getting this warning:
Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; Data_model has a deprecated constructor in

Here is the class in my file data_model.php
Class Data_model extends CI_Model {

    function data_model() {
        $this->load->database();
        $this->table_name = 'data';
    }

Open in new window


How would I call how would you do it?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
Change:
function data_model() {
to
function __construct() {
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
You can read more about this here
http://php.net/manual/en/migration70.deprecated.php
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
In older versions of PHP (pre 5 I think), the constructor (ctor) of a class was basically a function with the same name as the class:

class MyClass {
    public function MyClass()
    {
        // this is the CTOR and get's called whenever you create an instance of the class
    }
}

Open in new window

In your code, you have a function named the same as the class, so PHP is interpreting that to think you're creating a ctor, and it's telling you that way of doing things is outdated. The new way of creating a ctor is to use a function called __construct():

class MyClass {
    public function __construct()
    {
        // this is the CTOR and get's called whenever you create an instance of the class
    }
}

Open in new window

If you want the method to be a ctor, rename it to __construct(). If you want it to be a normal method, rename it to something other than the class name

Author

Commented:
Thank you for explaining.  It makes sense now.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial