How to code methods

The syntax

      [public | private | protected] function functionName ([parameterList]) { 
        // Statements to execute 
      }
      

A public method

      public function getSummary() { 
        $maxLength = 25; 
        $summary = $this->description; 
        if (strlen($summary) > $maxLength) { 
          $summary = substr($summary, 0, $maxLength - 3) . '...'; 
        }
        return $summary
      }
      

A private method

      private function internationalizePrice($country = 'US') {
        switch ($country) {
          case 'US':
            return '$' . number_format($this->price, 2); 
          case 'FR': 
            return number_format($this->price, 2, ',' , '.') . ' EUR'; 
          default: 
            return number_format($this->price, 2); 
        } 
      }
      

A method that accesses a property of the current object

      public function showDescription() {
        echo $this->description;
      }
      

A method that calls a method of the current object

      public function showPrice($country = 'US') {
        echo $this->internationalizePrice($country);
      }
      

Description

Back