define as follows
class Timer{
private static $timeRemaining;
private static $timeLimit;
private static $nextTime;
static function block();
static function updateCookies();
}
when going around between webpages, how long do those static properties and methods live?
As a result, which one is better, using the class above or a singleton object?
They live as much as PHP executes a code - while request lives.
And of course, between webpages all data is erased.
But you can use session and manually assign data to static variables or non-static instance variables.
Singletons use a static variable as a storage of instance.
Related
I am learning php and there are still alot of unclear areas for me in the language. I wonder when and why would we use private static properties inside the class. From what I understood private properties may only be accessed by the class where it was defined. So, the private part is clear, but the static is still unclear. In the docs it says:
Declaring class properties or methods as static makes them accessible
without needing an instantiation of the class. A property declared as
static cannot be accessed with an instantiated class object (though a
static method can).
Does that mean that I can access static properties without instantiation of the class. So, for example:
class Foo{
static $bar;
public function __construct($bar){
$this->bar = $bar;
}
So, I can access the $bar property of the class like so?
Foo::$bar
But, if I do this, it wouldn't work?
$foo = new Foo();
$foo::$bar
And, then if do make a property private static for which reason would we do that, since I thought we make them static in order to access them outside of their class and making them private would make that impossible. I would be very grateful if someone could clear this up to me.
When you declare a normal property, there is a different value of that property for every instance you create of that class (each object you create with new Foo). For a static property, there is one copy of that variable for the whole class.
This is separate from the visibility of that variable - a public static property exists once per class, and can be accessed from everywhere; a private static property exists once per class, but can only be accessed from inside that class's definition.
As a simple example, you could have a counter that gave each instance of the class a unique number. You don't need code outside the class to see or change this counter, so you mark it private, but it needs to be shared amongst all instances, so you mark it static.
class Foo {
// Static counter; shared with every instance
private static $nextID=0;
// Normal instance property: each instance will have its own value
private $myID;
public function __construct() {
// Set the ID for this instance to the next ID
$this->myID = self::$nextID;
// Increment the shared counter
self::$nextID++;
}
}
Static context within a PHP class (but outside of a function) is context which exists statically, that is without the need for a backing instance of an object.
Example:
class A {
public $a = 1;
public static $b = 2;
public function instanceFunction() {
A::$a; //Wrong way
$this->a //Right way
A::$b; //Works
self::$b; // Also works
static::$b; // Also also works
}
public static function staticFunction() {
A::$a; //Does not work
$this->a //Error $this within static context
A::$b; //Works
self::$b; // Also works
static::$b; // Also also works
}
}
A::$a; // Error $a is not static so it needs an instance of an object
A::$b; // Works
$Aobject=new A();
$Aobject->a; //Works
$Aobject->b // Does not work
Using self means "refer to the class I've written this in" e.g. in this case it's always A. Using static means "refer to the class I've called this from" which applies if static inheritance is involved which PHP does manage to pull off.
See the class definition below:
I am currently using 5.3.9 version of PHP
class A{
static function ab(){
echo "static function ab<br>";
}
public function xy(){
echo "public function xy<br>";
}
}
$obj = new A();
$obj->ab();
A::ab();
Both functions call give the same output without any error
static function ab
static function ab
How it is possible that static method can also be called by class object?
Because static method only calls by using class name only?!
Now what is the difference between accessing these two ways to call static method?
Referring to php.net website
Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can).
A big difference is
Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.
Refer to the page php.net/manual/en/language.oop5.static.php for more details
As long as you are just echoing a simple string, there's no difference, if your method will be declared static or public, since static method can also be called with the object instance. As of PHP 5.5 an error will raise if you call your public method with a static way. However, the static method can be called with classname::staticMethod() so the page should only know about the class, but not really needs an instance of it.
The other deal is the method content. As I said, if you just echo a string, you don't need a static method for that. A static method is out of the object context. That means you cannot access properties or methods from the current object via $this
I've got a comprehension question:
The singleton design pattern uses a static function call like Singleton::getInstance() and in this function it uses static variables like self::$_instance.
According to the definition, static functions and variables are independent of any concrete instances and are evoked each time just for the purpose of it's particular call. How then is it possible, that any value can be stored in such quasi-abstract and each-time-new-created 'objects'?
Hope you understood my question.
Static property is similar to global variable. Difference only of its visibilities. Global variable can changed by everybody as public static property, but private or protected static property has less visibility.
Imaginate that class is actually an object which created when defined and could exists only in one instance. Static properties and methods are properties and methods of this "object". That is why many people does not understand differnce between regular class with static members and singleton.
Visibility, static, singleton pattern
The Singleton design (anti-)pattern allows to make sure there is at most one instance created.
The property is static, therefore it can be accessed from a static method. However the underlying object is a real, live instance. From a static method, you cannot use $this, but you can refer to any already-instanciated object, which self::$_instance happens to be)
class SingletonClass {
private static $_instance;
private $_someProperty;
public static function getSomeProperty() {
return self::$_instance->_someProperty; // allowed, self::$_instance is static, but a real object nonetheless
}
}
Three things make the class Singleton or else it will a normal class.
Static variable
Static method
Private constructor
Probably you have created a class for counter functionality, Singleton is like the same.
Let say I have a class like the following:
class MyClass {
public function __construct($str) {
// do some stuff including:
$str = self::getIP($str);
}
private static function getIP($str) {
return (bool) ip2long($str) ? $str : gethostbyname($str);
}
// other NON static functions ....
}
In the above scenario what is the advantage/disadvantage of having getIP static vs simply:
private function getIP($str) {
return (bool) ip2long($str) ? $str : gethostbyname($str);
}
and calling $this->getIP(); in the constructor (or any other method)
Context: I would normally do this without the static keyword but I have come across this a couple of times recently. Just wondering if there was any advantage of using static when you are definitely not going to use this.
In this particular case I'm not sure. Usually I use static methods because:
It stores data in a static variable that I want accessible from several objects (sort of like a global)
I don't want to have to create an instance of the object every time I call that method - especially if it's mostly called from outside.
For example, I usually create an App object that has many helper methods. One of these is fetch_db. Every time I want to connect to the database I just call App::fetch_db().
In this specific case there is no advantage or disadvantage. However, a static method can be used by other static methods (perhaps some public static method). Are you sure it's not called by another static method?
Technically any method that has no reliance on $this can be static as long as it conforms to its interface (e.g. if a parent method relies on $this but the child method doesn't, the child method should not be static).
I understand that static means that an object doesn't need to be instantiated for that property/method to be available. I also understand how this applies to private properties and methods and public methods. What I'm trying to understand is what static private function gains you. For example:
class Beer {
static private $beertype = "IPA";
private function getBeerType() {
return self::$beertype;
}
static public function BeerInfo() {
return self::getBeerType();
}
}
print Beer::BeerInfo() . "\n";
The private method getBeerType() executes just fine without an instantiated object as long as it's being called from a static public method. If a static public method has access to all private methods (static and non-static), what's the benefit of declaring a method static private?
With strict error reporting turned on, I do get the warning that I should make getBeerType() static, although it still lets me run the code. And I did a little research and it seems like other languages (Java) will force you to declare a private method as static when called by a static public method. Looks like PHP lets you get away with this. Is there a way to force it to throw an error and not execute?
A static private method provides a way to hide static code from outside the class. This can be useful if several different methods (static or not) need to use it, i.e. code-reuse.
Static methods and static variables, sometimes called class methods and class variables, are a way of putting code and data into a kind of namespace. You could also think of class variables as variables attached to the class itself, of which there is (by definition) exactly one, instead of to instances of that class, of which there may be zero, one or many. Class methods and class variables can be useful in working with attributes that not just remain same in all instances, but actually be the same.
An example of a class variable is a database handler in an ORM entity object. All instances are their own object, but they all need access to the same database handler for loading and saving themselves.
Private versus public is a completely separate quality, which is I suspect what you're stumbling over. A private method cannot be called and private variables cannot be accessed from code outside the class. Private methods are usually used to implement "internal" logic on the object that must not be accessible from outside the object. This restriction can be needed by instance methods as well as class methods.
An example of a private class method could be in a factory method. There might be three factory calls for creating an object which might differ in parameters being supplied. Yet the bulk of the operation is the same. So it goes into a private static method that the non-private factory methods call.
I understand static means that an object doesn't need to be instantiated for that property/method to be available.
Everything static just exists. Globally.
I also understand how this applies to public properties and methods and public methods
Are you sure you have understood that it creates a global variable and a standard global function?
What I'm trying to understand is what static private function gains you.
The private is just a specifier of visibilityDocs. So that gains you visibility control.
Is it useful? Depends on the use-case.
it's for preventing OTHERS from consuming it.
Example, you have a Logger static object, then you have two public static methods LogOk and LogError and both benefeit from an "internal" method Log but you don't want the consumers of that class to be able to call Log directly.
You can call Logger::LogOk( "All right." ); but you cannot call Logger::Log( "abc" ); if Log is private.
You you can internally always make use of it from the same class.
Although the code works, it throws a Strict standards error:
Strict standards: Non-static method Beer::getBeerType() should not be
called statically
So, here you get the use of the private static.
Simply said you can declare a private static function if you have a repeated operation in some of the public static functions in the class.
Naturally if you are an inexperienced programmer or new to the OOP putting limitations to your code seem strange. But strict declarations like this will make your code cleaner and easier to maintain.
In large projects and complex classes you can appreciate to know exactly what to expect from a function and exactly how you can use it.
Here is a good read: Single responsibility principle and
God Object
Here's the rule and the best answer,
static methods cannot access non-static variables and methods, since these require an instance of the class. Don't worry about the warning, the rule is set and it will break your code in the future once it's fully enforced. That is why
static public function BeerInfo() {
return self::getBeerType()
is wrong,
you have to declare getBeerType as static.
In your example, you can simplify this by doing the following.
static private $beertype = "IPA";
static public function BeerInfo() {
return self::$beertype;
}
'static' purely means resident in a single region of memory. If you are memory conscious, static implementations are a good strategy.
When you use a public static function, chances are, most of the time, that you don't want to deal with an instance of that class, but want to re-use pre-existing functionality from within that class. Leveraging private static functions is the way to do that without instances.
However, you could have a public static function which accepts an argument which is an instance of said class, e.g.
static public function doSomething(Beer &$ref) {
$ref->instanceLevelFunction(...);
}