PHP SPL extension library (four) function

硬核项目经理
中文

Today we continue to learn the content of SPL, the content of this article is relatively simple about the content of a series of functions provided in SPL. In fact, in many previous articles, we have already touched some of the functions provided in SPL. This time we will learn more in detail.

Class information related functions

Functions related to class information are mainly functions for viewing some class information, and there is no function for operating class functions.

View class inheritance, interface, and characteristics

First, let's take a look. If we want to get which interface the current class implements, then we can directly use a class_implements().

interface A {}
interface B {}

class TestA implements A,B {}

var_dump(class_implements(new TestA));
// array(2) {
//     ["A"]=>
//     string(1) "A"
//     ["B"]=>
//     string(1) "B"
//   }

As you can see, it returns an array, showing the name of the interface implemented by our current class object. If the class we query does not implement any interface, then it returns an empty array.

var_dump(class_implements(new stdClass()));
// array(0) {
// }

Similarly, we can also view the parent class of a certain class object.

class C{}

class TestB extends C {}

var_dump(class_parents(new TestB));
// array(1) {
//     ["C"]=>
//     string(1) "C"
//   }

Although PHP is a single-inheritance language, the function class_parents() still returns an array. If the class object has no parent class, then an empty array is also returned.

class TestC {
    use D, E;
}

var_dump(class_uses(new TestC));
// array(2) {
//     ["D"]=>
//     string(1) "D"
//     ["E"]=>
//     string(1) "E"
//   }

Finally, we can also get the trait feature information used by the current class object through the class_uses() function.

Class hash and class ID

Students who have done Java development must have seen that all classes have a hashCode() method. The function of this method in Java is to return the hash code value of an object. It is usually used to determine whether objects are equal and unique. In Java, all classes inherit from the Object base class by default, and this base class comes with this method.

However, in PHP, classes do not have such a global base class, and naturally there is no such method. Obviously, we can only rely on other extension tools to help us provide such capabilities. Fortunately, it happens that such a function is provided in SPL.

var_dump(spl_object_hash(new TestA));
// string(32) "000000000ed109570000000025e36d74"

$a = new TestA;
var_dump(spl_object_hash($a));
// string(32) "000000000ed109570000000025e36d74"

var_dump(spl_object_id(new TestA));
// int(2)
var_dump(spl_object_id($a));
// int(1)

The spl_object_hash() function is used to obtain the Hash value of an object. It is a complete Hash value, unlike the Java hashCode() method that returns a numeric value. The returned content of objects instantiated by the same class template is the same.

spl_object_id() returns the ID of the object. Its result is different for different new, that is, the instantiated object. If the object always exists, its ID value will not change, and if the object is destroyed, the ID value will also be recycled and handed over to other objects for use. In fact, we can see the ID value by printing the object directly.

var_dump($a);
// object(TestA)#1 (0) {
// }
var_dump(new TestA);
// object(TestA)#2 (0) {
// }

The number after the pound sign is the ID value of our object, which is the content obtained by spl_object_id().

Get all available class information in the SPL library

This function returns all the class name information that can be used in the SPL library.

var_dump(spl_classes());
// array(55) {
//     ["AppendIterator"]=>
//     string(14) "AppendIterator"
//     ["ArrayIterator"]=>
//     string(13) "ArrayIterator"
//     ["ArrayObject"]=>
//     string(11) "ArrayObject"
//     ["BadFunctionCallException"]=>
//     string(24) "BadFunctionCallException"
//     ["BadMethodCallException"]=>
//     string(22) "BadMethodCallException"
//     ["CachingIterator"]=>
//     string(15) "CachingIterator"
//     ["CallbackFilterIterator"]=>
//     string(22) "CallbackFilterIterator"
//     ["DirectoryIterator"]=>
//     string(17) "DirectoryIterator"
//     ["DomainException"]=>
//     string(15) "DomainException"
//     ["EmptyIterator"]=>
//     string(13) "EmptyIterator"
//     ["FilesystemIterator"]=>
//     string(18) "FilesystemIterator"
//     ["FilterIterator"]=>
//     string(14) "FilterIterator"
//     ["GlobIterator"]=>
// …………………………
// …………………………

As you can see, many of the types of information we talked about can be seen here.

Iterator related functions

Iterator-related functions have actually appeared when I talked about iterators in the previous article, and that is the very useful iterator_to_array() function.

$iterator = new ArrayIterator(['a'=>'a1', 'b'=>'b1', 'c'=>'c1']);

var_dump(iterator_to_array($iterator, true));
// array(3) {
//     ["a"]=>
//     string(2) "a1"
//     ["b"]=>
//     string(2) "b1"
//     ["c"]=>
//     string(2) "c1"
//   }

We can imagine that inside this function, we actually use foreach() to traverse the iterator and return all the results in an array. This function also has a second parameter, its role is to make the keys not use the original key value, but use the default array subscript arrangement.

var_dump(iterator_to_array($iterator, false));
// array(3) {
//     [0]=>
//     string(2) "a1"
//     [1]=>
//     string(2) "b1"
//     [2]=>
//     string(2) "c1"
//   }

In addition to directly obtaining the result of the iterator traversal, we can also directly obtain the number of elements in the iterator through a function.

var_dump(iterator_count($iterator)); // int(3)

In fact, the iterator_count() function is like an iterator version of the count() function.

function printCaps($iterator){
    echo strtoupper($iterator->current()), PHP_EOL;
    return true;
}
iterator_apply($iterator, "printCaps", array($iterator));
// A1
// B1
// C1

The last iterator_apply() function allows us to traverse an iterator through a specified callback function.

Automatically load related functions

For the automatic loading function, we have already touched on the earliest article, that is, the series of articles about Composer. But at that time we only learned a spl_autoload_register() function. Today we will learn two more functions, but first let's take a look at the use of spl_autoload_register() function.

function autoloadA($class){
    if(is_file('./autoloadA/' . $class . '.php')){
        require_once './autoloadA/' . $class . '.php';
    }
    
}
spl_autoload_register('autoloadA');

spl_autoload_register(function($class){
    if(is_file('./autoloadB/' . $class . '.php')){
        require_once './autoloadB/' . $class . '.php';
    }
});

$sky = new Sky();
$sky->result();
// This is Sky PHP!

$planet = new Planet();
$planet->result();
// This is Planet PHP!

In this test code, we registered two spl_autoload_register() in the form of callback function and anonymous function. In this way, when we use classes that are not defined in the current file, we will look for them in these two autoloads. When we talked about Composer before, we said that spl_autoload_register() is better than \_\_autolod() because it maintains an autoload list, which is equivalent to multiple \_\_autoload() functions. We can see how many auto-loaded functions we have registered through another function.

var_dump(spl_autoload_functions());
// array(2) {
//     [0]=>
//     string(9) "autoloadA"
//     [1]=>
//     object(Closure)#3 (1) {
//       ["parameter"]=>
//       array(1) {
//         ["$class"]=>
//         string(10) "<required>"
//       }
//     }
//   }

Of course, it can be continuously registered or deleted.

spl_autoload_unregister('autoloadA');

var_dump(spl_autoload_functions());
// array(1) {
//     [0]=>
//     object(Closure)#3 (1) {
//       ["parameter"]=>
//       array(1) {
//         ["$class"]=>
//         string(10) "<required>"
//       }
//     }
//   }

Regarding the application of spl_autoload_register() in actual projects, that is, the application in Composer, interested students can move to the previous article.

Summarize

How about it, did you find that there are actually many functions that you have already come into contact with in your daily development and learning. These functions are the functions provided in the SPL extension library. In fact, through the study of these articles, we have discovered that the SPL extension library provides us with some basic data structures, iterators, and design patterns. The function encapsulation of the class, there are many things that are really simpler and more convenient than implementing it yourself, including the file operation and the implementation of design patterns that we will continue to learn in the next article.

Test code:

https://github.com/zhangyue0503/dev-blog/blob/master/php/2021/01/source/6. PHP's SPL extension library (four) function.php

Reference documents:

https://www.php.net/manual/zh/ref.spl.php

阅读 793
87 声望
16 粉丝
0 条评论
87 声望
16 粉丝
文章目录
宣传栏