Static method and class in php

PHP Static Methods and Properties

Summary: in this tutorial, you will learn about PHP static methods and static properties and understand the differences between the $this and self .

Introduction to PHP static methods and properties

So far, you have learned how to define a class that consists of methods and properties. To use the methods and properties of the class, you create an object and access these methods and properties via the object.

Since these methods and properties are bound to an instance of the class, they are called instance methods and properties.

PHP allows you to access the methods and properties in the context of a class rather than an object. Such methods and properties are class methods and properties.

Class methods and class properties are called static methods and properties.

Static methods

To define a static method, you place the static keyword in front of the function keyword as follows:

  class MyClass < public static function staticMethod()  < >> Code language: HTML, XML (xml)

Since a static method is bound to a class, not an individual instance of the class, you cannot access $this inside the method. However, you can access a special variable called self . The self variable means the current class.

The following shows how to call a static method from the inside of the class:

self::staticMethod(arguments);Code language: PHP (php)

To call a static method from the outside of the class, you use the following syntax:

className::staticMethod(arguments)Code language: JavaScript (javascript)
MyClass::staticMethod()Code language: CSS (css)

The following example defines the HttpRequest class that has a static method uri() that returns the URI of the current HTTP request:

class HttpRequest < public static function uri(): string < return strtolower($_SERVER['REQUEST_URI']); > >Code language: PHP (php)

The following calls the uri() static method of HttpRequest class:

echo HttpRequest::uri();Code language: PHP (php)

If the current HTTP request is https://www.phptutorial.net/php-static-method/ , the uri() method will return /php-static-method/ .

Static properties

To define a static property, you also use the static keyword:

public static $staticProperty;Code language: PHP (php)
class MyClass < public static $staticProperty; public static function staticMethod()  < >>Code language: PHP (php)

To access a public static property outside of the class, you also use the class name with the :: operator:

MyClass::$staticProperty;Code language: PHP (php)

Like the static methods, to access static properties from within the class, you use the self instead of $this as follows:

self::staticPropertyCode language: PHP (php)

self vs. $this

The following table illustrates the differences between the self and $this :

$this self
Represents an instance of the class or object Represents a class
Always begin with a dollar ($) sign Never begin with a dollar( $ ) sign
Is followed by the object operator ( -> ) Is followed by the :: operator
The property name after the object operator ( -> ) does not have the dollar ($) sign, e.g., $this->property . The static property name after the :: operator always has the dollar ( $ ) sign.

PHP static methods and properties example

Suppose that you want to create an App class for your web application. And the App class should have one and only one instance during the lifecycle of the application. In other words, the App should be a singleton.

The following illustrates how to define the App class by using the static methods and properties:

 class App < private static $app = null; private function __construct()  < >public static function get() : App < if (!self::$app) < self::$app = new App(); > return self::$app; > public function bootstrap(): void < echo 'App is bootstrapping. '; > >Code language: HTML, XML (xml)

First, define a static property called $app and initialize its value to null :

private static $app = null;Code language: PHP (php)

Second, make the constructor private so that the class cannot be instantiated from the outside:

private function __construct()  Code language: PHP (php)

Third, define a static method called get() that returns an instance of the App class:

public static function get() : App < if (!self::$app) < self::$app = new App(); > return self::$app; >Code language: PHP (php)

The get() method creates an instance of the App if it has not been created, otherwise, it just simply returns the App’s instance. Notice that the get() method uses the self to access the $app static property.

Fourth, the bootstrap() method is just for demonstration purposes. In practice, you can place the code that bootstraps the application in this method.

The following shows how to use the App class:

 $app = App::get(); $app->bootstrap();Code language: HTML, XML (xml)

In this code, we called the get() static method from the App class and invoked the bootstrap() method of the App ‘s instance.

Summary

  • Static methods and properties are bound to a class, not individual objects of the class.
  • Use the static keyword to define static methods and properties.
  • Use the self keyword to access static methods and properties within the class.

Источник

Ключевое слово «static»

Эта страница описывает использование ключевого слова static для определения статических методов и свойств. static также может использоваться для определения статических переменных и позднего статического связывания. Для получения информации о таком применении ключевого слова static пользуйтесь вышеуказанными страницами.

Объявление свойств и методов класса статическими позволяет обращаться к ним без создания экземпляра класса. Атрибут класса, объявленный статическим, не может быть доступен посредством экземпляра класса (но статический метод может быть вызван).

В целях совместимости с PHP 4, сделано так, что если не использовалось определение области видимости, то член или метод будет рассматриваться, как если бы он был объявлен как public.

Так как статические методы вызываются без создания экземпляра класса, то псевдо-переменная $this не доступна внутри метода, объявленного статическим.

Доступ к статическим свойствам класса не может быть получен через оператор ->.

При попытке вызова нестатических методов статически выводится предупреждение уровня E_STRICT .

Как и любая другая статическая переменная PHP, статические свойства могут инициализироваться только используя литерал или константу, выражения же недопустимы. Таким образом вы можете инициализировать статическое свойство например целым числом или массивом, но не сможете указать другую переменную, результат вызова функции или объект.

Начиная с версии PHP 5.3.0 существует возможность ссылаться на класс используя переменную. Поэтому значение переменной в таком случае не может быть ключевым словом (например, self, parent и static).

Пример #1 Пример статического свойства

class Foo
public static $my_static = ‘foo’ ;

public function staticValue () return self :: $my_static ;
>
>

class Bar extends Foo
public function fooStatic () return parent :: $my_static ;
>
>

$foo = new Foo ();
print $foo -> staticValue () . «\n» ;
print $foo -> my_static . «\n» ; // Не определено свойство my_static

print $foo :: $my_static . «\n» ; // Начиная с PHP 5.3.0
$classname = ‘Foo’ ;
print $classname :: $my_static . «\n» ; // Начиная с PHP 5.3.0

print Bar :: $my_static . «\n» ;
$bar = new Bar ();
print $bar -> fooStatic () . «\n» ;
?>

Пример #2 Пример статического метода

Foo :: aStaticMethod ();
$classname = ‘Foo’ ;
$classname :: aStaticMethod (); // Начиная с PHP 5.3.0
?>

Источник

Create and Use Static Classes in PHP

Create and Use Static Classes in PHP

  1. Create Static Class With Static Variables in PHP
  2. Create Static Class With Static Method in PHP
  3. Create Static Class and Call the Static Method on Another Class in PHP
  4. Create Static Class and Call the Static Method on a Child Class Using the parent Keyword

In PHP, a static class is a class that is only instantiated once in a program. It must have a static member ( variable ), static member function ( method ), or both.

Create Static Class With Static Variables in PHP

Let’s create a class and initialize four variables. We will then access them using the class name.

 php  class Person    //intialize static variable  public static $name = "Kevin";  public static $age = 23;  public static $hobby = "soccer";  public static $books = "HistoryBooks"; >   // print the static variables  echo Person::$name .'
'
;
echo Person::$age .'
'
;
echo Person::$hobby .'
'
;
echo Person::$books .'
'
;
?>
Kevin 23 soccer HistoryBooks 

Create Static Class With Static Method in PHP

We will initialize a method called simpleProfile() . Then call the method using the class name.

 php class Person   public static function simpleProfile()   echo "I am a programmer and loves reading historical books.";  > >  // Call static method  Person::simpleProfile(); ?> 
I am a programmer and loves reading historical books. 

Create Static Class and Call the Static Method on Another Class in PHP

We call the swahiliMan() method on another class using the class name .

 php class greetings   public static function swahiliGreeting()   echo "Habari Yako!";  > >  class swahiliMan   public function greetings()   greetings::swahiliGreeting();  > >  $swahiliman1 = new swahiliMan();  $swahiliman1->greetings(); ?> 

Create Static Class and Call the Static Method on a Child Class Using the parent Keyword

We instantiate a method with the static variable. After that, call the method using the parent keyword and assign it to a variable on a child class that extends the static class.

class Person   protected static function getCountry()   return "Australia";  > > // a child class, extends the Person class  class Student extends Person   public $country;  public function __construct()   $this->country = parent::getCountry();  > >  $student = new Student;  echo $student -> country; ?> 

Related Article — PHP Class

Источник

Читайте также:  Html small font text
Оцените статью