Hướng dẫn dùng double colon trong PHP

Static classes trong php

Vì class có thể được khởi tạo nhiều lần, giá trị của một class là duy nhất đối với instance/object, chứ không phải là class. Điều này cũng có nghĩa là bạn không thể sử dụng method hoạc variable mà không khởi tạo class, nhưng vẫn có một ngoại lệ. Cả method và variable trong class đều được cho là static, có nghĩa là chúng có thể được sử dụng mà không instantiating lớp đầu ticần khởi tạo lớpên. Nếu làm thế này thì variable có thể được truy cập mà không cần class cụ thể, nên sẽ chỉ có một phiên bản duy nhất của variable này. Vấn đề của static method là sẽ không thể truy cập vào các variable và method khác vì không có class cụ thể.

Trong phần trước, chúng tôi đã viết User class. Chúng ta sẽ mở rộng nó với một số static function để xem sự khác biệt:

name ." is ".$this->age ." years old";
    }
    
    publicstaticfunction ValidatePassword($password)
    {
        if(strlen($password) >= self::$minimumPasswordLength)
            returntrue;
        elsereturnfalse;
    }
}

$password="test";
if(User::ValidatePassword($password))
    echo"Password is valid!";
elseecho"Password is NOT valid!";
?> 

Chúng ta đã cho thêm một static variable vào class, $minimumPasswordLength được đặt là 6 thì chúng ta có một static function để kiểm tra khi nào dòng password là hợp lệ.

Như bạn thấy, để truy cập vào static function từ static method, chúng tôi prefix nó với từ khóa. Vì nó chỉ hoạt động trong class, do đó, để gọi function ValidatePassword () từ bên ngoài class, chúng tôi sử dụng tên của class. Bạn cũng sẽ nhận thấy rằng việc tiếp cận các static member yêu cầu double-colon operator -> operator, nhưng cũng không có nhiều khác biệt lắm.

Class constants

Constant là một variable không thể thay dổi. Khi bạn tạo constant, bạn cho nó một value và valua này không bao giờ thay đổi.Bình thường thì các variable khác dễ sử dụng hơn, nhưng có có những lúc vẫn cần đến constant, ví dụ như để nhắc nhở lập trình viên (bản thân hay những người khác) là variable nay không được phép thay đổi trong lúc chạy trương trình.

Class constant cũng giống như constant bình thường, có điều  họ được gọi trong class vì vậy chỉ truy cập qua một class nhất định. Giống như static member, bạn dùng double-colon operator để vào class constant. Ví dụ:

Như bạn thấy, qua trình cũng như tạo variable vậy, chỉ có điều là không cần access modifier – một constant luôn luôn có sẵn. Để dùng constant, chúng ta viết tên của class, dùng double-colon operator rồi viết tên của constant.

The “final” keyword

Trong các phần trước chúng ta đã biết cách inherit từ class này sang class kia, viết lại function đã được inherit từ class khác. Nhưng trong một số trường hợp, bạn không muốn class khác inherit, hoặc không muốn function được inherit bị sửa chữa. Nếu vậy, bạn có thể dùng từ khóa ‘final’ và PHP sẽ bão lỗi nếu ai đó sưa chửa final class hoạc final function của bạn.

Final class sẽ giống như này:

finalclass Animal
{
    public$name;
}

Và class với final function sẽ giống thế này:

class Animal

class Animal
{
    finalpublicfunction Greet()
    {
        return"The final word!";    
    }
}

Bạn có thể gộp cả hai hoạc sử dụng riêng lẻ như ví dụ trên.

Bài dịch từ PHP5 Tutorial 

To supplement the answers regarding PHP's use of two colons as its "scope resolution operator":

In addition, a double colon is used:

  1. To resolve an unqualified, qualified, or aliased class name to its fully qualified form, and

  2. To invoke a class's "__callStatic" method with an arbitrary, previously undeclared method name.

To resolve a class name to its fully qualified form by appending "::class"

Two colons followed by the "class" keyword, placed after the name of a class, provides that class's fully qualified name as a string. I.e., "ClassName::class" resolves to the fully qualified name of "ClassName". See: (A) Manual: Classes and Objects: Basics, (B) Manual: Classes and Objects: Class Constants, and (C) Manual: Language Reference: Constants

The syntax was adopted in PHP 5.5. See: (A) RFC and (B) PHP 5.5 New Features

The "::class" syntax is useful within a namespace to obtain the fully qualified name of a class from its unqualified or qualified form, or from an alias of its name.

The "::class" syntax seems to work to resolve interface names as well as class names, although that does not appear to be documented by the sources linked above.

Within a class, the syntax also works with "self::class", as mentioned by the "::class" RFC linked above.

A few examples:

fullName(), PHP_EOL;
// outputs: MyNamespace\TheirClass

To invoke "__callStatic" with an undeclared method name

Two colons can be used to "call" a static method name that a class has not declared. E.g., "ClassName::arbitraryMethodName()". Doing so invokes the class's "__callStatic" method, if the class has declared one. It also passes to __callStatic the name of the undeclared method and any arguments passed to the undeclared method. The __callStatic method then may "dynamically" choose how to handle the call. PHP refers to this as "overloading" with the __callStatic "magic method".

See additional StackOverflow discussion

Example:

handleOrder($arguments);
        }

        return "I'm sorry, we can't help you with " .
            lcfirst($item) . ".";
    }
}

namespace OurCompany\Specialists;

class Car
{
    public function handleOrder($arguments)
    {
        return "May I help you with a $arguments[0] car?";
    }
}

class Truck
{
    public function handleOrder($arguments)
    {
        return "May I help you with a $arguments[0] truck?";
    }
}

use OurCompany\Orders\Intake;

echo Intake::orderCar("red"), PHP_EOL;
// outputs: May I help you with a red car?

echo Intake::orderTruck("pickup"), PHP_EOL;
// outputs: May I help you with a pickup truck?

echo Intake::orderShoes("suede"), PHP_EOL;
// outputs: I'm sorry, we can't help you with shoes.