PHP Coding Standards – How to Avoid Mistakes Using the Same Variable Name Again

coding-standardscoding-stylemistakesPHP

This isn't a rare case and occurs with me often and I spent countless time trying to debug the code.

Latest example, this PHP code where I used $email for the parameter and for object as well.

private function _mail( $email )
{
    if( filter_var( $email, FILTER_VALIDATE_EMAIL ) ):
        $email = new Zend_Mail();
        $email->setSubject( $this->request->post('subject') )
            ->setBodyHtml( $this->request->post('message') )
            ->setFrom( $this->request->post('from') )
            ->addTo( $email )
            ->send();
        unset($email);
    endif;
}

It was throwing an error, strtr() expects parameter 1 to be an string object given and it was really frustrating to browse through zend libraries to see what obscure string statement was throwing this error.

How to avoid such mistakes?

Best Answer

One good aspect of modern programming languages is that you can have large variable names. In Object oriented programming, which you are utilising, Java conventions are quite popular.

So it would be better to have a descriptive name for the Zend_Mail object, such as

$zendMail = new Zend_Mail();

In the beginning it will consume a bit more time until the brain shifts making it a habit, but that time will have a huge return of investment and stress from having to debug similar cases.

Related Topic