swape.net alireza balouch

22Mar/100

My PHP Code-Standards Part 2

Classses

Class name and and file name should have the same name.

Let us say you have a class called "myFirstClass" then your file should be myFirstClass.class.php

Remember to have some kind of comment on top of the file to describe important information about the class like author, version nr or created date.

  1.  
  2. class myFirstClass{
  3.    private $intNumber = 3;
  4.    private $strName = '';
  5.  
  6.   public function getNumber(){
  7.      return $this->intNumber ;
  8.   }
  9. }
  10.  

Never access the internal variables directly. Use a public function to get or set the value.

  1.  
  2. class someClass{
  3.    private $intValue1 = 0;
  4.    private $intValue2 = 0;
  5.  
  6.    public function getValue1(){
  7.       return $this->intValue1;
  8.    }
  9.  
  10.    public function getValue2(){
  11.       return $this->intValue2;
  12.    }
  13.  
  14. }
  15.  

Use default values instead of passing the same value every time.

  1.  
  2. class someClass{
  3.    private $intValue1 = 0;
  4.    private $intValue2 = 0;
  5.  
  6.    public function getDate($strFormat = 'Y-m-d' ){
  7.       return date($strFormat);
  8.   }
  9.  
  10. }
  11.  

Never echo out within a function. It is better to return a value.
This way you can choose what to do with returned value.

  1.  
  2.  
  3. $objSome = new someClass();
  4. $strReturn = 'Date: <b>' . $objSome->getDate() . '</b><br/>';
  5. $strReturn .= 'Week: <b>' . $objSome->getDate('W') . '</b>';
  6.  
  7. echo $strReturn;
  8.  
  9. class someClass{
  10.    public function getDate($strFormat = 'Y-m-d' ){
  11.       return date($strFormat);
  12.   }
  13. }
  14.  
Tagged as: Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.