Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
653 views
in Technique[技术] by (71.8m points)

oop - When do I use static variables/functions in php?

I am refreshing myself on OOP with PHP and I saw an example of setting functions and/or variables as static. When and why would I set a variable/function to static? I've done other languages and don't really recall ever using static, I never found a real purpose to it. I know what it does but why not just use a variable instead?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You use static when you want to use a method / variable that is not tied to an instance. That can happen when :

  • There is no relation with your purpose and an instance (useful for toolboxes in languages that doesn't allow anything else that OOP like Java, but not useful in PHP).

  • You want to control the access to the instance. Most often, the instance you want to deal with is not defined when you write the code, but will be at execution. The Singleton pattern is the best example. You can use static methods as factories to create an object according to the context or sharing resources with other instances. E.G : a static member can give access to a data base layer so part of the app accesses the same one from anywhere and it's opened/closed without conflicts.

  • Performances matter and the method will be executed a lot of times. In that case, you will save some CPU time preventing the interpreter from looking up the member to an instance at each call. But still, if perfs becomes such an issues that you come to this solution, it might time to reconsider your architecture, or the use of a binding to a faster language for the critical parts of the code.

  • You have a method that is related to a type but will be applied to another. It can make sense to write the method into the declaration of the first type, but set it static since it expects an instance of the another one.

The perfect example is a String parser :

class MyObject 
{
 static function parse($str)
 {
    $obj = new MyObject();
    // some parsing/setting happens here
    return $obj;
 }
}

// you create an object "MyObject" from a string, so it's more obvious
// to read it this way :
$new_obj = MyObject::parse("This a description of a super cool object");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...