Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modern way to declare a class in php

Tags:

php

class

Wanting to make sure I'm using classes properly. The main script accepts this from the user:

1. month
2. year
3. the type of event they want to find (microsoft or linux)

For the program to find a microsoft event it has to run the regular expression: '(ID=)+[0-9]+' For the program to find a linux event it has to run the regular expression: '(ID=)+[A-F]+'

Creating an Events class seems a logical way to organize the code. I don't want to send the required regular expression into the class from the main script if possible. I want to tell the events class if it is a microsoft or linux event and let the class return the processed data based on variables that are pre-defined in the class for each type of event.

I have existing code written as:

 class Events
    {
            var $month;
            var $year;
            var $event_identifier_expression;

      public function events($month, $year)
      {
       $this->month = $month;
       $this->year = $year;
       return $this->event_identifier_expression.$month.$year;
      }
    }

I want to use something like multiple static helper methods in the Events class instead. If I change the existing code to the code below, will it allow me to call microsoft_events and linux_events independently from outside the class, and is this correct way to create the class? (example code for calling the static functions from outside the class is appreciated) :

class Events
    {
            public function __construct()
            {var $month;
             var $year;
             var $event_identifier_expression;
            } 

      public static function microsoft_events($month, $year)
      {
       $this->month = $month;
       $this->year = $year;
       $this->event_identifier_expression = '(ID=)+[0-9]+';
       return $this->event_identifier_expression.$month.$year;
      }
      public static function linux_events($month, $year)
      {
       $this->month = $month;
       $this->year = $year;
       $this->event_identifier_expression = '(ID=)+[A-F]+';
       return $this->event_identifier_expression.$month.$year;
      }
    }
like image 916
JMC Avatar asked Aug 13 '10 08:08

JMC


1 Answers

If you want to use everything statically (which makes it essentially a prettied up procedural piece of code), you'll have to do something like this:

class Events
{
   static protected $month;
   static protected $year;

   public static function microsoft_events($month, $year)
   {
      self::$month = $month;
      self::$year = $year;
   }
   public static function linux_events($month, $year)
   {
      self::$month = $month;
      self::$year = $year;
   }
}

Events::microsoft_events(12, 2010);

Note that you can only have a single instance then, every call will change the values for everything.

like image 149
Blizz Avatar answered Nov 01 '22 17:11

Blizz