php中常见的魔术常量

tech2023-12-05  34

php中常见的魔术常量

PHP provides a set of special predefined constants and magic methods to your programs. Unlike the constants you would set using define(), the value of the constants depend on where they are used in your code and are used to access read-only information about your code and PHP. The magic methods are reserved method names you can use in your classes to hook into special PHP functionality.

PHP为您的程序提供了一组特殊的预定义常量和魔术方法。 与使用define()设置的常量不同,这些常量的值取决于它们在代码中的使用位置以及用于访问有关代码和PHP的只读信息。 magic方法是保留的方法名称,您可以在您的类中使用它们来挂钩特殊PHP功能。

If you haven’t heard about PHP’s magic methods and constants yet, then this article is for you! I’ll review some of the more useful ones and how you can use them in your code.

如果您还没有听说过PHP的魔术方法和常量,那么本文适合您! 我将回顾一些更有用的代码,以及如何在代码中使用它们。

预定义常量 (Predefined Constants)

The predefined constants are used to access information about your code. The constants here are written in all capital letters between double underscores, like __LINE__ and __FILE__ for example. Here are some of the useful constants that are made available by PHP:

预定义的常量用于访问有关代码的信息。 此处的常数以双下划线之间的所有大写字母表示,例如__LINE__和__FILE__ 。 以下是PHP提供的一些有用的常量:

__LINE__ returns the line number in the source file the constant appears at, like this:

__LINE__返回源文件中常量所在的行号,如下所示:

<?php echo "line number: " . __LINE__; // line number: 2 echo "line number: " . __LINE__; // line number: 3 echo "line number: " . __LINE__; // line number: 4

__FILE__ represents the name of your file, including its full path, like this:

__FILE__代表文件的名称,包括其完整路径,如下所示:

<?php echo "the name of this file is: " . __FILE__; // the directory and name of file is: C:wampwwwindex.php

__DIR__ represents only the path to the file:

__DIR__仅表示文件的路径:

<?php echo "the directory of this file is: " . __DIR__; // the directory of this file is: C:wampwww

__CLASS__ returns the name of the current class:

__CLASS__返回当前类的名称:

<?php class Sample { public function __construct() { echo __CLASS__; } } $obj = new Sample(); // Sample

__FUNCTION__ returns the name of the current function:

__FUNCTION__返回当前函数的名称:

<?php function mySampleFunc() { echo "the name the function is: " . __FUNCTION__; } mySampleFunc(); //the name of function is: mySampleFunc

__METHOD__ represents the name of the current method:

__METHOD__代表当前方法的名称:

<?php class Sample { public static function myMethod() { echo "the name of method is: " . __METHOD__; } } Sample::myMethod(); // the name of the method is: myMethod

__NAMESPACE__ returns the name of the current namespace:

__NAMESPACE__返回当前名称空间的名称:

<?php namespace MySampleNS; echo "the namespace is: " . __NAMESPACE__; // the name space is: MySampleNS

魔术方法 (Magic Methods)

Magic methods provide hooks into special PHP behavior. Unlike the constants earlier, their names are written in lower/camel-case letters with two leading underscores, like __construct() and __destruct().

魔术方法提供了特殊PHP行为的钩子。 与之前的常量不同,它们的名称用小写/驼峰字母书写,并带有两个下划线,例如__construct()和__destruct() 。

__construct() is magic method which PHP invokes to create object instances of your class. It can accept any number of arguments.

__construct()是魔术方法,PHP调用该方法来创建您的类的对象实例。 它可以接受任意数量的参数。

<?php class MySample { public function __construct($foo) { echo __CLASS__ . " constructor called with $foo."; } } $obj = new MySample(42); // MySample constructor called with 42

As its name implies, the __destruct() method is called when the object is destroyed by PHP’s garbage collector. It accepts no arguments, and it is commonly used to perform any clean up operations that may be needed such as closing a database connection.

顾名思义,当PHP的垃圾回收器销毁对象时,将调用__destruct()方法。 它不接受任何参数,通常用于执行可能需要的任何清理操作,例如关闭数据库连接。

<?php class MySample { public function __destruct() { echo__CLASS__ . " destructor called."; } } $obj = new MySample; // MySample destructor called

Our next magic methods deal with property overloading, and provide a way for PHP to handle calls to properties and methods that have not been defined (or are not accessible to us).

我们的下一个魔术方法处理属性重载,并为PHP提供一种方法来处理对尚未定义(或我们无法访问)的属性和方法的调用。

PHP invokes the __get() method if a property is undefined (or inaccessible) and called in a getter context. The method accepts one argument, the name of the property. It should return a value which is treated as the value of the property.

如果属性未定义(或无法访问)并在getter上下文中调用, __get() PHP调用__get()方法。 该方法接受一个参数,即属性的名称。 它应该返回一个值,该值被视为属性的值。

The __set() method is called for undefined properties in a setter context. It accepts two arguments, the property name and a value.

在setter上下文中为未定义的属性调用__set()方法。 它接受两个参数,属性名称和值。

<?php class MySample { private $myArray = array(); public function __set($prop, $value) { $this->myAarray[$prop] = $value; } public function __get($prop) { return $this->myArray[$prop]; } public function __isset($prop) { return isset($this->myArray[$prop]); } public function __unset($prop) { unset($this->myArray[$prop]); } public function __toString() { return __CLASS__ . ":" . $this->name; } } $obj = new MySample(); if (!isset($obj->name)) { $obj->name = "Alireza"; } echo $obj->name; // Alireza echo $obj; // MySample:Alireza

In the above example code, the property name is not defined in the class. I attempt to assign the value “mysample” to it, and PHP invokes the magic method __set(). It receives “name” as the $prop argument and “Alireza” as $value, and I store the value in the private $myArray array. The __get() method works in a similar fashion; when I output $obj->name, the __get() method is called and “name” is passed in for the $prop argument.

在上面的示例代码中,属性name未在类中定义。 我尝试为其分配值“ mysample”,PHP调用了魔术方法__set() 。 它接收“名称”作为$prop参数,接收“ Alireza”作为$value ,并将该值存储在私有$myArray数组中。 __get()方法的工作方式与此类似。 当我输出$obj->name ,将__get()方法,并为$prop参数传递“ name”。

There are other magic methods which help us with retrieving and inspecting inaccessible member variables as well which appear in the sample code: __isset(), __unset(), and __toString(). Both __isset() and __unset() are triggered by the functions with the same name (sans the underscores) in PHP.

还有其他魔术方法可以帮助我们检索和检查示例代码中出现的不可访问的成员变量: __isset() , __unset()和__toString() 。 __isset()和__unset()均由PHP中具有相同名称(不含下划线)的函数触发。

__isset() checks whether the property is set or not, and accepts one argument which is the property we want to test. __unset()receives one argument which is the name of the property that the program wants to unset.

__isset()检查是否设置了属性,并接受一个参数,即我们要测试的属性。 __unset()接收一个参数,该参数是程序要取消设置的属性的名称。

In many cases, representing an object as string is useful, such as for output to a user or another process. Normally PHP presents them as ID in memory, which is not good for us. The __toString() method helps us represent the object as a string. The method is triggered in any situation where an object is used as a string, for example: echo "Hello $obj". It can also be called directly like any other normal public method, which is preferable to hacks such as appending an empty string to force coercion.

在许多情况下,将对象表示为字符串很有用,例如用于输出给用户或其他进程。 通常,PHP在内存中将它们显示为ID,这对我们不利。 __toString()方法可帮助我们将对象表示为字符串。 在将对象用作字符串的任何情况下都会触发该方法,例如: echo "Hello $obj" 。 也可以像其他任何普通公共方法一样直接调用它,它比黑客(例如添加空字符串强制强制)更可取。

摘要 (Summary)

OOP programming can produce more maintainable and testable code. It helps us create better and standard PHP code. Also, it makes it possible to take advantage of the magic methods and constants which PHP makes available.

OOP编程可以产生更多可维护和可测试的代码。 它可以帮助我们创建更好的标准PHP代码。 此外,它还可以利用PHP提供的不可思议的方法和常量。

Image via Stepan Kapl / Shutterstock

图片来自Stepan Kapl / Shutterstock

翻译自: https://www.sitepoint.com/magic-methods-and-predefined-constants-in-php/

php中常见的魔术常量

相关资源:PHP的魔术常量__METHOD__简介
最新回复(0)