PHP Static objects and methods

时间:2016-04-04 18:44:59

标签: php methods properties static

I was wondering when I should use static methods and properties instead of 'normal' properties and methods. I know that static methods can be called without creating an instance of an object but I can't seem to find another example when to use static methods or properties.

Can somebody explain the static keyword with some examples how and when to use it (or not)?

2 个答案:

答案 0 :(得分:1)

Values of static proptery's are shared over all classes of the same type:

class foo{
  static $bar;

  function __construct($set = null){
    if($set){
      self::$bar = $set;
    }

    echo self::$bar;
  }
}

$a = new foo(1); // 1
$b = new foo();  // 1

They are very useful to hold (for example) a resources to share across the entire class, like a database connection. It can also be used for keeping statistics on how many calls have been made to a specific function, etc.

Now static methods are useful for keeping a code grouped inside the same scope, interacting with the class that may not need the instance of the class to function. They may for example return a static variable that holds an instance of a class. Because they are essentially methods, they are bound to follow interfaces and you can force a class to have a static method called getInstance() to have the same flow as other one-time classes. (hint, it works great with traits)

答案 1 :(得分:0)

Static methods are handy when the method doesn't change the state of the object.

class yourMom{
    public $name;
    function __construct($name, $ageInYears){
         $this->name = $name;
         $this->age_in_days = self::yearsToDays($ageInYears);
    }

    private static yearsToDays($years){
        return 365 * $years;
    }
}

In this example it's basically a helper function.

相关问题