user8348171
user8348171

Reputation:

Is is a good practice to call a method inside another method? - PHP

I would like to know if it's recommended to do this:

class User {

    public function __construct() {
        parent::__construct();
    }
    public function exists($token) {
        //return true if token exists otherwise return false
    }
    public function createSession($token) {
        if($this->exists($token))
            //create session
        else
            //redirect
    }
}

I think it could be not recommended in case of a change in the exists method of the class but I think that'll not happen, What do you recommend me to do?

Upvotes: 1

Views: 1564

Answers (2)

winnie damayo
winnie damayo

Reputation: 426

I do that all the time, when i notice my method is too long i segregate it and create another private method or protected method. Another reason is so it could be reuse for another method.

Here's an example:

class Download extends PHPExcel{

    public function excel2007()
    {
        $excelFormat = $this->excelFormat();
    }

    public function excel2003()
    {
        $excelFormat = $this->excelFormat();
    }

    private function excelFormat()
    {
        return [

            'font_bold' => [

                'font' => array(
                    'bold' => true
                )

            ],
            'font_size' => [

                'font' => array(
                    'size' => 10
                )   

            ],
            'align_center' => [

                'alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER)    

            ]
        ];
    }
}

Upvotes: 0

Barmar
Barmar

Reputation: 781004

There's nothing wrong with calling methods from other methods. In many designs, it's critical that you do this. This allows you to create subclasses that redefine the method, and the new definition will be called.

So if you do:

class SpecialUser extends User {
    public function exists($token) {
        // determine token existence in some other way
    }
}

You can then do:

$s = new SpecialUser;
$s->createSession($someToken);

and it will make use of the special way that SpecialUser checks tokens.

Upvotes: 4

Related Questions