php融合jpg与php_PHP的反思与反思

php融合jpg与php

Introspection is a common feature in any programming language which allows object classes to be manipulated by the programmer. You’ll find introspection particularly useful when you don’t know which class or method you need to execute at design time.

自省是任何编程语言中的常见功能,它允许程序员对对象类进行操作。 当您不知道在设计时需要执行哪个类或方法时,内省特别有用。

Introspection in PHP offers the useful ability to examine classes, interfaces, properties, and methods. PHP offers a large number functions that you can use to accomplish the task. In order to help you understand introspection, I’ll provide a brief overview of some of PHP’s classes, methods, and functions using examples in PHP to highlight how they are used.

PHP中的自省功能提供了检查类,接口,属性和方法的有用功能。 PHP提供了大量功能,您可以使用它们来完成任务。 为了帮助您理解内省,我将使用PHP中的示例简要介绍一些PHP的类,方法和函数,以突出显示它们的用法。

During this article, you’ll see a couple examples of how to use some of the most useful PHP’s introspection function and a section dedicated to an API that offers functionality similar to introspection, the Reflection API.

在本文中,您将看到几个有关如何使用一些最有用PHP自省功能的示例,以及一个专门介绍API的部分,该API提供与自省类似的功能,即反射API。

PHP自省功能 (PHP Introspection Functions)

In the first example, I’ll demonstrate a handful of PHP’s introspection functions. You can use these functions to extract basic information about classes such as their name, the name of their parent class, and so on.

在第一个示例中,我将演示一些PHP的自省功能。 您可以使用这些函数来提取有关类的基本信息,例如它们的名称,其父类的名称,等等。

  • class_exists() – checks whether a class has been defined

    class_exists() –检查是否已定义一个类

  • get_class() – returns the class name of an object

    get_class() –返回对象的类名称

  • get_parent_class() – returns the class name of an object’s parent class

    get_parent_class() –返回对象的父类的类名称

  • is_subclass_of() – checks whether an object has a given parent class

    is_subclass_of() –检查对象是否具有给定的父类

Here is the example PHP code that contains the definition for Introspection and Child classes and outputs information extracted by the functions listed above:

这是示例PHP代码,其中包含Introspection类和Child类的定义,并输出上述功能提取的信息:

<?php
class Introspection
{
    public function description() {
        echo "I am a super class for the Child class.n";
    }
}

class Child extends Introspection
{
    public function description() {
        echo "I'm " . get_class($this) , " class.n";
        echo "I'm " . get_parent_class($this) , "'s child.n";
    }
}

if (class_exists("Introspection")) {
    $introspection = new Introspection();
    echo "The class name is: " . get_class($introspection) . "n"; 
    $introspection->description();
}

if (class_exists("Child")) {
    $child = new Child();
    $child->description();

    if (is_subclass_of($child, "Introspection")) {
        echo "Yes, " . get_class($child) . " is a subclass of Introspection.n";
    }
    else {
        echo "No, " . get_class($child) . " is not a subclass of Introspection.n";
    }
}

The output of the above code should be as follows:

以上代码的输出应如下所示:

The class name is: Introspection
I am a super class for the Child class.
I'm Child class.
I'm Introspection's child.
Yes, Child is a subclass of Introspection.

You can determine whether or not the given class has been defined using the class_exists() method, which takes a string argument representing the name of the desired class to check, and an optional Boolean value whether or not to call the autoloader in the process.

您可以使用class_exists()方法确定给定的类是否已定义,该方法使用一个字符串参数表示要检查的所需类的名称,以及一个可选的布尔值,该布尔值是否在过程中调用自动加载器。

The get_class() and get_parent_class() methods return the class name of an object or its parent’s class name respectively. Both takes as arguments an object instance.

get_class()get_parent_class()方法分别返回对象的类名或其父类的类名。 两者都以对象实例作为参数。

The is_subclass_of() methods takes an object instance as its first argument and a string, representing the parent class name, and returns whether the object belongs to a class which is a subclass of the class given as argument.

is_subclass_of()方法将一个对象实例作为其第一个参数,并使用一个字符串表示父类名称,并返回该对象是否属于作为参数给定的类的子类的类。

Here’s a second example containing the definition for a ICurrencyConverter interface and GBPCurrencyConverter class and outputs information extracted by the functions listed above. As with the first example, I’ll list the functions first and then show you some code.

这是第二个示例,其中包含ICurrencyConverter接口和GBPCurrencyConverter类的定义,并输出由上述功能提取的信息。 与第一个示例一样,我将首先列出这些函数,然后向您展示一些代码。

  • get_declared_classes() – returns a list of all declared classes

    get_declared_classes() –返回所有已声明类的列表

  • get_class_methods() – returns the names of the class’ methods

    get_class_methods() –返回类的方法的名称

  • get_class_vars() – returns the default properties of a class

    get_class_vars() –返回类的默认属性

  • interface_exists() – checks whether the interface is defined

    interface_exists() –检查接口是否已定义

  • method_exists() – checks whether an object defines a method

    method_exists() –检查对象是否定义了方法

<?php
interface ICurrencyConverter
{
    public function convert($currency, $amount);
}

class GBPCurrencyConverter implements ICurrencyConverter
{
    public $name = "GBPCurrencyConverter";
    public $rates = array("USD" => 0.622846,
                          "AUD" => 0.643478);
    protected $var1;
    private $var2;

    function __construct() {}

    function convert($currency, $amount) {
        return $rates[$currency] * $amount;
    }
}

if (interface_exists("ICurrencyConverter")) {
    echo "ICurrencyConverter interface exists.n";
}

$classes = get_declared_classes();
echo "The following classes are available:n";
print_r($classes);

if (in_array("GBPCurrencyConverter", $classes)) {
    print "GBPCurrencyConverter is declared.n";
 
    $gbpConverter = new GBPCurrencyConverter();

    $methods = get_class_methods($gbpConverter);
    echo "The following methods are available:n";
    print_r($methods);

    $vars = get_class_vars("GBPCurrencyConverter");
    echo "The following properties are available:n";
    print_r($vars);

    echo "The method convert() exists for GBPCurrencyConverter: ";
    var_dump(method_exists($gbpConverter, "convert"));
}

The output of the above code should be as follows:

以上代码的输出应如下所示:

ICurrencyConverter interface exists.
The following classes are available:
Array
(
    [0] => stdClass
    [1] => Exception
    [2] => ErrorException
    [3] => Closure
    [4] => DateTime
    [5] => DateTimeZone
    [6] => DateInterval
    [7] => DatePeriod
    ...
    [154] => GBPCurrencyConverter
)
GBPCurrencyConverter is declared.
The following methods are available:
Array
(
    [0] => __construct
    [1] => convert
)
The following properties are available:
Array
(
    [name] => GBPCurrencyConverter
    [rates] => Array
        (
            [USD] => 0.622846
            [AUD] => 0.643478
        )
)
The method convert() exists for GBPCurrencyConverter: bool(true)

As you may have guessed, the interface_exists() method is very similar to class_exists() discussed in the first example. It determines whether or not the given interface has been defined and takes a string argument for the interface name and an optional autoloader Boolean.

您可能已经猜到了, interface_exists()方法与第一个示例中讨论的class_exists()非常相似。 它确定是否已定义给定的接口,并为接口名称和可选的autoloader布尔值使用字符串参数。

The get_declared_classes() method returns an array with the names of all of the defined classes and takes no arguments. Depending on what libraries you have loaded (either complied into PHP or loaded with require/include), additional classes could be present.

get_declared_classes()方法返回一个数组,其中包含所有已定义类的名称,并且不带参数。 根据您已加载的库(已编译到PHP或已加载require / include),可能会出现其他类。

The get_class_method() takes either an object instance or a string as argument representing the desired class and returns an array of method names defined by the class.

get_class_method()以对象实例或字符串作为表示所需类的参数,并返回由该类定义的方法名称的数组。

Notice that from all the properties defined in the ICurrencyConverter class and returned by the get_class_vars() method, only $name and $rates appeared in the output. The private and protected properties were skipped.

请注意,在ICurrencyConverter类中定义并由get_class_vars()方法返回的所有属性中,仅$name$rates出现在输出中。 私有和受保护的属性被跳过。

PHP反射API (PHP Reflection API)

PHP supports reflection through its Reflection API. As you can see from the PHP manual, the Reflection API is much more generous then introspection and offers a large number of classes and methods that you can use to accomplish reflection tasks. The ReflectionClass class is the main class of the API and is used to apply reflection over classes, interfaces, and methods and to extract information about all class components. Reflection is easy to implement in your application code and, like introspection, is also very intuitive.

PHP通过其Reflection API支持反射。 从PHP手册中可以看到,Reflection API比自省要宽泛得多,并且提供了大量可用于完成反射任务的类和方法。 ReflectionClass类是API的主要类,用于对类,接口和方法进行反射,并提取有关所有类组件的信息。 反射很容易在您的应用程序代码中实现,并且像自省一样,也非常直观。

Here is an example to illustrate reflection using the same definitions for the ICurrencyConverter interface and the Child and GBPCurrencyConverter classes:

这是一个示例,用于说明对ICurrencyConverter接口以及ChildGBPCurrencyConverter类使用相同定义的反射:

<?php
$child = new ReflectionClass("Child");
$parent = $child->getParentClass();
echo $child->getName() . " is a subclass of " . $parent->getName() . ".n";

$reflection = new ReflectionClass("GBPCurrencyConverter");
$interfaceNames = $reflection->getInterfaceNames();
if (in_array("ICurrencyConverter", $interfaceNames)) {
    echo "GBPCurrencyConverter implements ICurrencyConverter.n";
}

$methods = $reflection->getMethods();
echo "The following methods are available:n";
print_r($methods);

if ($reflection->hasMethod("convert")) {
    echo "The method convert() exists for GBPCurrencyConverter.n";
}

The output of the above code should be as follows:

以上代码的输出应如下所示:

Child is a subclass of Introspection.
GBPCurrencyConverter implements ICurrencyConverter.
The following methods are available:
Array
(
    [0] => ReflectionMethod Object
        (
            [name] => __construct
            [class] => GBPCurrencyConverter
        )

    [1] => ReflectionMethod Object
        (
            [name] => convert
            [class] => GBPCurrencyConverter
        )

)
The method convert() exists for GBPCurrencyConverter.

The getInterfaceNames() method returns an array with interface names that a class implements. The getParentClass() method can return a ReflectionClass object representation of the parent class or false if there is no parent. To list the name of the ReflectionClass object, you use the getName() method, as you have seen in the above code.

getInterfaceNames()方法返回一个带有类实现的接口名称的数组。 getParentClass()方法可以返回父类的ReflectionClass对象表示形式;如果没有父类,则返回false。 如上面的代码所示,要列出ReflectionClass对象的名称,请使用getName()方法。

The getMethods() method retrieves an array of methods and can take as an optional argument a bitmask combination of ReflectionMethod::IS_STATIC, IS_PUBLIC, IS_PROTECTED, IS_PRIVATE, IS_ABSTRACT, and IS_FINAL to filter the list based on visibility.

getMethods()方法检索方法数组,并且可以将ReflectionMethod::IS_STATICIS_PUBLICIS_PROTECTEDIS_PRIVATEIS_ABSTRACTIS_FINAL的位掩码组合用作可选参数,以根据可见性过滤列表。

The Reflection API provides a good implementation of reflection giving you the ability to create more complex applications, such as ApiGen, though further discussion is beyond this goal of this article.

Reflection API提供了很好的反射实现,使您能够创建更复杂的应用程序,例如ApiGen ,尽管进一步的讨论超出了本文的目标。

摘要 (Summary)

In this article you’ve seen how to use PHP’s introspection functions and Refection API to obtain information about classes, interfaces, properties, and methods. The purpose of pulling this information is to gain greater insight into your code at run time and to create complex applications.

在本文中,您已经了解了如何使用PHP的自省功能和Refection API获取有关类,接口,属性和方法的信息。 提取此信息的目的是在运行时更深入地了解您的代码并创建复杂的应用程序。

Image via Fotolia

图片来自Fotolia

翻译自: https://www.sitepoint.com/introspection-and-reflection-in-php/

php融合jpg与php

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值