PHP原生类是指在PHP编程语言中自带的类库,提供了丰富的功能和方法,可以直接使用,不需要额外安装或引入其他第三方类库。 以下是一些常用的PHP原生类和它们的主要功能:
针对每个类的具体代码示例:
- $dateTime = new DateTime();
- echo $dateTime->format('Y-m-d H:i:s');
- $iterator = new FilesystemIterator('/path/to/directory');
- foreach($iterator as $fileinfo) {
- echo $fileinfo->getFilename() . "\n";
- }
- $dsn = 'mysql:host=localhost;dbname=test';
- $username = 'root';
- $password = '';
- try {
- $dbh = new PDO($dsn, $username, $password);
- $stmt = $dbh->prepare('SELECT * FROM users');
- $stmt->execute();
- while ($row = $stmt->fetch()) {
- echo $row['username'] . "\n";
- }
- } catch (PDOException $e) {
- echo 'Connection failed: ' . $e->getMessage();
- }
- $data = [
- 'name' => 'John',
- 'age' => 25,
- 'email' => 'john@example.com'
- ];
- $jsonString = json_encode($data);
- echo $jsonString;
- $decodedData = json_decode($jsonString, true);
- echo $decodedData['name']; // Output: John
- class CustomSessionHandler implements SessionHandlerInterface {
- // Implement the required methods
- }
- $handler = new CustomSessionHandler();
- session_set_save_handler($handler, true);
- session_start();
- $file = new SplFileObject('/path/to/file.txt', 'r');
- while (!$file->eof()) {
- echo $file->fgets();
- $file->next();
- }
- $xml = '
-
PHP Basics -
John Doe - ';
- $simpleXML = new SimpleXMLElement($xml);
- echo $simpleXML->title;
- // Access XML elements using array syntax
- echo $simpleXML['author'];
- $zip = new ZipArchive();
- $zipFileName = 'archive.zip';
- $zip->open($zipFileName, ZipArchive::CREATE);
- $zip->addFile('/path/to/file1.txt', 'file1.txt');
- $zip->addFile('/path/to/file2.txt', 'file2.txt');
- $zip->close();