문제

I'm trying to figure out what static vars are.

They can be access without instantiating the class but what other benefits do they have and when should they be used?

For example, my class has a private var which holds the name of the twitter feed i'm trying to get.

Should this be static? It never needs to change.

도움이 되었습니까?

해결책 2

Static variables are for when you want a variable inside a function to keep it's value if the function is called again.

An example of a static variable could be the following.

function addOne(){
    static $i = 0;
    $i++;
    return $i;
}

echo addOne();
echo addOne();
echo addOne();

Which would return

123

Without the static keyword, this would simply return

111

In your question, you mention you have data that won't need to be changed. As the comments in the question state, you should make this a Constant.

다른 팁

Generally things which aren't instance specific but needs to be stored in a variable should be static variables. Otherwise this manual tells the details: http://php.net/manual/en/language.variables.scope.php

Otherwise you can consider using constants also. For the example you mentioned (as others wrote) using constants seems to be the most sensible. (Either a class constant, or simple one.)

In short, static variables can be used for constants.

For example, a Math class can have static variables; PI etc.

Let's say you have something in a class that you need later.

Now, you need that thing but you don't actually need|want|should create a new instance of that class.

That's why you use a static method/property

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top