PHP: Static and non Static functions and Objects

What's the difference between these object callings?

Non Static:

$var = new Object;
$var->function();

Static:

$var = User::function();

And also inside a class why should I use the static property for functions?

example:

static public function doSomething(){
    ...code...
}

Static functions, by definition, cannot and do not depend on any instance properties of the class. That is, they do not require an instance of the class to execute (and so can be executed as you've shown without first creating an instance). In some sense, this means that the function doesn't (and will never need to) depend on members or methods (public or private) of the class.


Difference is in the variable scope. Imagine you have:

class Student{
    public $age;
    static $generation = 2006;

   public function readPublic(){
       return $this->age;  
   }

   public static function readStatic(){
       return $this->age;         // case 1
       return $student1->age;    // case 2 
       return self::$generation;    // case 3 

   }
}

$student1 = new Student();
Student::readStatic();
  1. You static function cannot know what is $this because it is static. If there could be a $this, it would have belonged to $student1 and not Student.

  2. It also doesn't know what is $student1.

  3. It does work for case 3 because it is a static variable that belongs to the class, unlike previous 2, which belong to objects that have to be instantiated.


Static methods and members belong to the class itself and not to the instance of a class.