PHP 内置类是指在 PHP 核心库中预定义的类,这些类可以直接在 PHP 脚本中使用,无需额外安装或引入外部库。PHP 提供了丰富的内置类,涵盖了文件操作、数据库连接、字符串处理、日期时间处理、异常处理等多个方面。
以下是一些常见的 PHP 内置类及其用途:
DateTime
类:
$date = new DateTime(); echo $date->format('Y-m-d H:i:s');
PDO
类:
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
Exception
类:
try { throw new Exception("An error occurred"); } catch (Exception $e) { echo $e->getMessage(); }
SplFileObject
类:
$file = new SplFileObject("example.txt"); echo $file->fgets();
ArrayObject
类:
$array = new ArrayObject([1, 2, 3]); $array->append(4);
DirectoryIterator
类:
$dir = new DirectoryIterator('/path/to/dir'); foreach ($dir as $fileinfo) { echo $fileinfo->getFilename(); }
ReflectionClass
类:
$reflection = new ReflectionClass('MyClass'); var_dump($reflection->getMethods());
SimpleXMLElement
类:
$xml = new SimpleXMLElement('<root><child>value</child></root>'); echo $xml->child;
ZipArchive
类:
$zip = new ZipArchive(); $zip->open('example.zip', ZipArchive::CREATE); $zip->addFile('file.txt'); $zip->close();
SoapClient
类:
$client = new SoapClient("http://example.com/soap.wsdl"); $result = $client->__soapCall('methodName', $params);
这些内置类极大地简化了 PHP 开发中的常见任务,开发者可以直接使用这些类来完成各种操作,而无需从头编写代码。