What is a static class php?

Tip

This page describes the use of the static keyword to define static methods and properties. static can also be used to define static variables and for late static bindings. Please refer to those pages for information on those meanings of static.

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. These can also be accessed statically within an instantiated class object.

Static methods

Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside methods declared as static.

Warning

Calling non-static methods statically throws an Error.

Prior to PHP 8.0.0, calling non-static methods statically were deprecated, and generated an E_DEPRECATED warning.

Example #1 Static method example

Static properties

Static properties are accessed using the Scope Resolution Operator [::] and cannot be accessed through the object operator [->].

It's possible to reference the class using a variable. The variable's value cannot be a keyword [e.g. self, parent and static].

Example #2 Static property example

Output of the above example in PHP 8 is similar to:

foo
foo

Notice: Accessing static property Foo::$my_static as non static in /in/V0Rvv on line 23

Warning: Undefined property: Foo::$my_static in /in/V0Rvv on line 23

foo
foo
foo
foo

inkredibl

14 years ago

Note that you should read "Variables/Variable scope" if you are looking for static keyword use for declaring static variables inside functions [or methods]. I myself had this gap in my PHP knowledge until recently and had to google to find this out. I think this page should have a "See also" link to static function variables.
//www.php.net/manual/en/language.variables.scope.php

payal001 at gmail dot com

11 years ago

Here statically accessed property prefer property of the class for which it is called. Where as self keyword enforces use of current class only. Refer the below example:

artekpuck at gmail dot com

4 years ago

It is worth mentioning that there is only one value for each static variable that is the same for all instances

admin at shopinson dot com

2 years ago

I used instantiation to access the access the a static property directly.

A Simple ticky art, you may apply [using object to access static property in a class] with the scope resolution operator


print $my_class::$myconstant;

Anonymous

17 years ago

You misunderstand the meaning of inheritance : there is no duplication of members when you inherit from a base class. Members are shared through inheritance, and can be accessed by derived classes according to visibility [public, protected, private].

The difference between static and non static members is only that a non static member is tied to an instance of a class although a static member is tied to the class, and not to a particular instance.
That is, a static member is shared by all instances of a class although a non static member exists for each instance of  class.

Thus, in your example, the static property has the correct value, according to principles of object oriented conception.
class Base
{
  public $a;
  public static $b;
}

class Derived extends Base
{
  public function __construct[]
  {
    $this->a = 0;
    parent::$b = 0;
  }
  public function f[]
  {
    $this->a++;
    parent::$b++;
  }
}

$i1 = new Derived;
$i2 = new Derived;

$i1->f[];
echo $i1->a, ' ', Derived::$b, "\n";
$i2->f[];
echo $i2->a, ' ', Derived::$b, "\n";

outputs
1 1
1 2

Anonymous

8 years ago

It should be noted that in 'Example #2', you can also call a variably defined static method as follows:

ASchmidt at Anamera dot net

4 years ago

It is important to understand the behavior of static properties in the context of class inheritance:

- Static properties defined in both parent and child classes will hold DISTINCT values for each class. Proper use of self:: vs. static:: are crucial inside of child methods to reference the intended static property.

- Static properties defined ONLY in the parent class will share a COMMON value.



will output:
Parent: parent_only=fromchild, both_distinct=fromparent
Child: parent_only=fromchild, both_distinct=fromchild, child_only=fromchild

rahul dot anand77 at gmail dot com

6 years ago

To check if a method declared in a class is static or not, you can us following code. PHP5 has a Reflection Class, which is very helpful.

try {
    $method = new ReflectionMethod[ 'className::methodName ];
    if [ $method->isStatic[] ]
    {
        // Method is static.
    }
}
catch [ ReflectionException $e ]
{
    //    method does not exist
    echo $e->getMessage[];
}

*You can read more about Reflection class on //php.net/manual/en/class.reflectionclass.php

davidn at xnet dot co dot nz

13 years ago

Static variables are shared between sub classes

sideshowAnthony at googlemail dot com

6 years ago

The static keyword can still be used [in a non-oop way] inside a function. So if you need a value stored with your class, but it is very function specific, you can use this:

class aclass {
    public static function b[]{
        static $d=12; // Set to 12 on first function call only
        $d+=12;
        return "$d\n";
    }
}

echo aclass::b[]; //24
echo aclass::b[]; //36
echo aclass::b[]; //48
echo aclass::$d; //fatal error

tolean_dj at yahoo dot com

11 years ago

Starting with php 5.3 you can get use of new features of static keyword. Here's an example of abstract singleton class:

webmaster at removethis dot weird-webdesign dot de

12 years ago

On PHP 5.2.x or previous you might run into problems initializing static variables in subclasses due to the lack of late static binding:



This will output:
A::$a = lala; B::$a =

If the init[] method looks the same for [almost] all subclasses there should be no need to implement init[] in every subclass and by that producing redundant code.

Solution 1:
Turn everything into non-static. BUT: This would produce redundant data on every object of the class.

Solution 2:
Turn static $a on class A into an array, use classnames of subclasses as indeces. By doing so you also don't have to redefine $a for the subclasses and the superclass' $a can be private.

Short example on a DataRecord class without error checking:



I hope this helps some people who need to operate on PHP 5.2.x servers for some reason. Late static binding, of course, makes this workaround obsolete.

manishpatel2280 at gmail dot com

8 years ago

In real world, we can say will use static method when we dont want to create object instance.

e.g ...

validateEmail[$email] {
if[T] return true;
return false;
}

//This makes not much sense
$obj = new Validate[];
$result = $obj->validateEmail[$email];

//This makes more sense
$result = Validate::validateEmail[$email];

ssj dot narutovash at gmail dot com

14 years ago

It's come to my attention that you cannot use a static member in an HEREDOC string.  The following code

class A
{
  public static $BLAH = "user";

  function __construct[]
  {
    echo

gratcypalma at gmail dot om

11 years ago

michalf at ncac dot torun dot pl

17 years ago

Inheritance with the static elements is a nightmare in php. Consider the following code:



What would you expect as an output? "foo"? wrong. It is "bar"!!! Static variables are not inherited, they point to the BaseClass::$property.

At this point I think it is a big pity inheritance does not work in case of static variables/methods. Keep this in mind and save your time when debugging.

best regards - michal

Jay Cain

12 years ago

Regarding the initialization of complex static variables in a class, you can emulate a static constructor by creating a static function named something like init[] and calling it immediately after the class definition.

Mirco

12 years ago

The simplest static constructor.

Because php does not have a static constructor and you may want to initialize static class vars, there is one easy way, just call your own function directly after the class definition.

for example.

valentin at balt dot name

12 years ago

How to implement a one storage place based on static properties.

jkenigso at utk dot edu

8 years ago

It bears mention that static variables [in the following sense] persist:



Note that $c::$a=2 changed the value of $b::$a even though $b and $c are totally different objects.

michael at digitalgnosis dot removethis dot com

17 years ago

If you are trying to write classes that do this:



Then you'll find that PHP can't [unless somebody knows the Right Way?] since 'self::' refers to the class which owns the /code/, not the actual class which is called at runtime. [__CLASS__ doesn't work either, because: A. it cannot appear before ::, and B. it behaves like 'self']

But if you must, then here's a [only slightly nasty] workaround:



Note that Base::Foo[] may no longer be declared 'static' since static methods cannot be overridden [this means it will trigger errors if error level includes E_STRICT.]

If Foo[] takes parameters then list them before $class=__CLASS__ and in most cases, you can just forget about that parameter throughout your code.

The major caveat is, of course, that you must override Foo[] in every subclass and must always include the $class parameter when calling parent::Foo[].

vvikramraj at yahoo dot com

14 years ago

when attempting to implement a singleton class, one might also want to either
a] disable __clone by making it private
b] bash the user who attempts to clone by defining __clone to throw an exception

Mathijs Vos

14 years ago



Please note, this won't work.
Use self::$myStaticClass = new bar[]; instead of self::myStaticClass = new bar[]; [note the $ sign].
Took me an hour to figure this out.

fakhar_anwar123 at hotmail dot com

2 years ago

Asnwer selcted as correct solves problem. There is a valid use case [Design Pattern] where class with static member function needs to call non-static member function and before that this static members should also instantiate singleton using constructor a constructor.

**Case:**
For example, I am implementing Swoole HTTP Request event providing it a call-back as a Class with static member. Static Member does two things; it creates Singleton Object of the class by doing initialization in class constructor, and second this static members does is to call a non-static method 'run[]' to handle Request [by bridging with Phalcon]. Hence, static class without constructor and non-static call will not work for me.

What does static mean in PHP?

The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.

What is a static class?

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new operator to create a variable of the class type.

What is static and final in PHP?

final static declares a method which is static [can be called without an instance of the class] and final [can't be overridden by subclasses]. static alone can be used to define a class-scoped variable, which isn't constant [but variables can't be final ].

Can we make an object of static class in PHP?

How to create a static class? It's fairly simple. The variables and methods that are declared and defined within a class are to be declared as static with the use of static keyword, so that they can be used without instantiating the class first.

Chủ Đề