Simple OOP Question

Discussion in 'PHP' started by ColorWP.com, Nov 1, 2011.

  1. #1
    Solved! View solution.
    ColorWP.com, Nov 1, 2011 IP
  2. #2
    You would typically use the :: when accessing static methods, or constant properties.

    
    
    class MyClass
    {
    
        public function showConstant()
        {
            
        }
    
    }
    
    $class = new MyClass();
    $class->showConstant();
    
    class MyClass
    {
        public static function showConstant()
        {
            
        }
    }
    
    echo MyClass::showConstant();
    
    
    PHP:
    With regard to that specific page on php.net, you can access the method using either :: or ->, but I would always use -> when accessing a non-static method just to avoid ambiguity in your code. Accessing a constant property using :: is acceptable.
     
    jestep, Nov 1, 2011 IP
    www.Andro.ws likes this.
  3. sarahk

    sarahk iTamer Staff

    Messages:
    28,899
    Likes Received:
    4,555
    Best Answers:
    123
    Trophy Points:
    665
    #3
    Back in my early PHP days I used to put all my functions that related to a particular type of data into a class but not invoke it, just use the class as a way to keep them neat and tidy. Still valid I guess but these days I'm more likely to invoke the class and let it set values and do a bit more.

    
    class MyClass {
       var $first_use = true;
    
       function getFirstUseFlag() {
          $output = $this->first_use;
          $this->first_use = false;
          return $output;
       }
    }
    $stuff = array('apples','oranges','lemons');
    $class = new MyClass();
    foreach($stuff as $val) {
       if ($class->getFirstUseFlag()) echo "<h1>New Heading</h1>";
       echo "<p>{$val}</p>";
    }
    PHP:
    Obviously, another very simplistic example, but hopefully it helps.
     
    sarahk, Nov 5, 2011 IP