Skip to content
Advertisement

PHP Methods and Class Design [closed]

Which design concept is better in PHP; passing variable to the function myFunct() or not passing the variable?

<?php
class A{
  public $myvar=1;
  public function myFunc($myvar){
    $this->myvar=$myvar+1;
  }
}
$myA=new A();
$myA->myFunc($myA->myvar);

// OR THIS ONE

class A{
  public $myvar=1;
  public function myFunc(){
    $this->myvar=$this->myvar+1;
  }
}
$myA=new A();
$myA->myFunc();

?>

Here is maybe a better example of what I am trying to understand:

class PhotosBasicClasses{
    protected $srcImage;    
    protected $fileImageTypeFlag;    
    public function createThumb($srcImage,$fileImageTypeFlag){    
         $this->srcImage=$srcImage;
         $this->fileImageTypeFlag=$fileImageTypeFlag;
         $resourceNewImage=$this->imageCreateFromFormat($srcImage,$fileImageTypeFlag);  //with or without the parameters is better?!
    
    }
    protected function imageCreateFromFormat($srcImage,$fileImageTypeFlag){   
        switch($fileImageTypeFlag){   //this is my problem: would be better to use the class variable or the internal variable($fileImageTypeFlag or $this->fileImageTypeFlag )
            case 'jpeg': return imagecreatefromjpeg($srcImage);break;
            case 'png': return imagecreatefrompng($srcImage);break;
            case 'gif': return imagecreatefromgif($srcImage);break;
            default: return "error  source file format";
                        }
}

Advertisement

Answer

Generally keep at class scope variables describing your class and usually required by most of your “important”(methods tha also describe what the class can do or has) methods.

At first glance, in your case the method imageCreateFromFormat($srcImage,$fileImageTypeFlag) looks fine and self contained . But the method createThumb if all it does is what you posted then remove it along with the two class variables and rename the other method to createThumb.

If it is unfinished and after calling the method imageCreateFromFormat is going to crop the image and create a thumbnail, then there is no reason to have class scope variables you can remove them unless you plan to rename the class and add a bunch of methods that use these two variables.

Finally, care must be taken with class names, it is not good practice to use plural and the word class.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement