Inhaltsverzeichnis
动态特性的重要性The importance of being dynamic
写一个柔性类Writing a bendy class
传统的数据库访问方式Classic database access
引入一点动态A little dab of dynamic
完全动态化Going completely dynamic
还可以改进的地方Room for improvement
Heim php教程 php手册 PHP语言的动态特性

PHP语言的动态特性

Jun 06, 2016 pm 07:51 PM
http php 动态 特性 语言

http://www.ibm.com/developerworks/xml/library/os-php-flexobj/ PHP5引入的面向对象的编程特性显著的提升了PHP语言的层次。不只是成员和方法的访问控制private, protected, public -- 和Java, C++, 或C#一样 -- 你同时还能创建运行期间能动态改变的对象,

http://www.ibm.com/developerworks/xml/library/os-php-flexobj/


PHP5引入的面向对象的编程特性显著的提升了PHP语言的层次。不只是成员和方法的访问控制private, protected, public -- 和Java, C++, 或C#一样 -- 你同时还能创建运行期间能动态改变的对象,动态的创建一个新的方法和属性。这些是Java, C++, 或C#语言无法提供的。这种语言能力使得类似于ROR这样的快速开发框架变得可能。


在进入正题之前,先提个醒:这篇文章涉及PHP5里面很高级的OOP特性使用,而这些特性并非在所有的应用程序中都会使用。而且,这些特性比较难以理解,如果你对OOP没有深刻理解的话,至少你得初步了解PHP对象的语法。

动态特性的重要性The importance of being dynamic


对象是双刃剑。一方面,对象是很好的封装数据和逻辑的方法,创建系统更直观且更易于维护。另一方面,它也可能会引起类膨胀,代码变得琐碎,需要编写大量重复性的代码,你只能希望中间不犯错误。这个问题的一个典型例子就是数据库访问和操作的对象。一般而言,你需要为每一张表创建一个简单的类,提供CRUD等方法。但也有另外的方法,创建一个空对象,设置属性,然后插入数据库。

比如你有一张表Customers, 你得创建一个Customer对象,拥有表中字段所对应的属性,代表单个客户。这个Customer对象允许你insert, update或者delete相应的数据库记录。这看来不错,能工作,但有一堆代码要写。如果你有20张表,那么你需要写20个类。

有三个方法来解决这个问题。第一个方法copy/paste/modify,对于小工程,这没什么。第二个方法是使用代码生成器读取数据库方案然后自动为你生成代码,很多开发框架提供代码生成器,这是个好主意。第三个方法,也就是本文所述,是通过编写一个简单的类,在运行时根据给定表的字段动态模型化。这个类比之前的特定表格的模型类性能上要差点,但是代码精简了很多。这个方法对于设计经常变动的项目特别合算。

那么,怎么写一个柔韧的类呢?

写一个柔性类Writing a bendy class


对象拥有两个方面:成员变量和方法。对于传统的编译语言,如Java,如果你想调用一个不存在的方法或者一个不存在的成员变量,会报编译错误。对于PHP,情况如何呢?

PHP的一个方法调用,工作方式如下。首先,PHP解释器查看该类的方法,如果方法存在,那么直接调用。否则,调用该类的魔法函数__call如果该方法存在的话,如果调用失败,则调用父类的方法,以此类推。

魔法函数是特定命名的方法,这个方法由PHP解释器在脚本执行的特定节点所触发。

最常见的魔法函数是对象创建时调用的构造函数。


__call方法有两个参数:请求方法名和参数。通过__call机制实现和自己写一个方法,对函数调用者而言,效果是一样的。这样,你可以创建一个包含"无数"方法的对象。

除了__call方法, 其他魔法函数,如__get 和 __set, 是在引用不存在的实例变量的时候被调用。记住这一点,你可以开始写适用于任何数据库表访问的类了。

(以下主要是代码重构,保持原文)


传统的数据库访问方式Classic database access


Let's start with a simple database schema. The schema shown in Listing 1 is for a single data-table database that holds a list of books.

Listing 1. The MySQL database schema

DROP TABLE IF EXISTS book;
CREATE TABLE book (
        book_id INT NOT NULL AUTO_INCREMENT,
        title TEXT,
        publisher TEXT,
        author TEXT,
        PRIMARY KEY( book_id )
);


Load this schema into a database named bookdb.

Next, write a conventional database class that you will then modify to become dynamic. Listing 2 shows a simple database access class for the book table.

Listing 2. The basic database access client

<?php require_once("DB.php");

$dsn = 'mysql://root:password@localhost/bookdb';
$db =& DB::Connect( $dsn, array() );
if (PEAR::isError($db)) { die($db->getMessage()); }

class Book
{
  private $book_id;
  private $title;
  private $author;
  private $publisher;

  function __construct()
  {
  }

  function set_title( $title ) { $this->title = $title; }
  function get_title( ) { return $this->title; }

  function set_author( $author ) { $this->author = $author; }
  function get_author( ) { return $this->author; }

  function set_publisher( $publisher ) {
  $this->publisher = $publisher; }
  function get_publisher( ) { return $this->publisher; }

  function load( $id )
  {
    global $db;
$res = $db->query( "SELECT * FROM book WHERE book_id=?",
    array( $id ) );
    $res->fetchInto( $row, DB_FETCHMODE_ASSOC );
    $this->book_id = $id;
    $this->title = $row['title'];
    $this->author = $row['author'];
    $this->publisher = $row['publisher'];
  }

  function insert()
  {
    global $db;
    $sth = $db->prepare(
'INSERT INTO book ( book_id, title, author, publisher )
    VALUES ( 0, ?, ?, ? )'
    );
    $db->execute( $sth,
      array( $this->title,
        $this->author,
        $this->publisher ) );
    $res = $db->query( "SELECT last_insert_id()" );
    $res->fetchInto( $row );
    return $row[0];
  }

  function update()
  {
    global $db;
    $sth = $db->prepare(
'UPDATE book SET title=?, author=?, publisher=?
   WHERE book_id=?'
    );
    $db->execute( $sth,
      array( $this->title,
        $this->author,
        $this->publisher,
        $this->book_id ) );
  }

  function delete()
  {
    global $db;
    $sth = $db->prepare(
      'DELETE FROM book WHERE book_id=?'
    );
    $db->execute( $sth,
      array( $this->book_id ) );
  }

  function delete_all()
  {
    global $db;
    $sth = $db->prepare( 'DELETE FROM book' );
    $db->execute( $sth );
  }
}

$book = new Book();
$book->delete_all();
$book->set_title( "PHP Hacks" );
$book->set_author( "Jack Herrington" );
$book->set_publisher( "O'Reilly" );
$id = $book->insert();
echo ( "New book id = $id\n" );

$book2 = new Book();
$book2->load( $id );
echo( "Title = ".$book2->get_title()."\n" );
$book2->delete( );
?>
Nach dem Login kopieren

To keep the code simple, I put the class and the test code in one file. The file starts with getting the database handle, which it stores in a global variable. The Book class is then defined, with private member variables for each field. A set of methods for loading, inserting, updating, and deleting rows from the database is also included.

The test code at the bottom starts by deleting all the entries from the database. Next, the code inserts a book, telling you the ID of the new record. Then, the code loads that book into another object and prints the title.

Listing 3 shows what happens when you run the code on the command line with the PHP interpreter.

Listing 3. Running the code on the command line

% php db1.php
New book id = 25
Title = PHP Hacks
%


Not much to look at, but it gets the point across. The Book object represents a row in the book data table. By using the fields and the methods above, you can create new rows, update them, and delete them.

引入一点动态A little dab of dynamic


The next step is to make the class a bit dynamic by creating the get_ and set_ methods on the fly for the individual fields. Listing 4 shows the updated code.

Listing 4. Dynamic get_ and set_ methods

<?php require_once("DB.php");

$dsn = 'mysql://root:password@localhost/bookdb';
$db =& DB::Connect( $dsn, array() );
if (PEAR::isError($db)) { die($db->getMessage()); }

class Book
{
  private $book_id;
  private $fields = array();

  function __construct()
  {
    $this->fields[ 'title' ] = null;
    $this->fields[ 'author' ] = null;
    $this->fields[ 'publisher' ] = null;
  }

  function __call( $method, $args )
  {
    if ( preg_match( "/set_(.*)/", $method, $found ) )
    {
      if ( array_key_exists( $found[1], $this->fields ) )
      {
        $this->fields[ $found[1] ] = $args[0];
        return true;
      }
    }
    else if ( preg_match( "/get_(.*)/", $method, $found ) )
    {
      if ( array_key_exists( $found[1], $this->fields ) )
      {
        return $this->fields[ $found[1] ];
      }
    }
    return false;
  }

  function load( $id )
  {
    global $db;
$res = $db->query( "SELECT * FROM book WHERE book_id=?",
   array( $id ) );
    $res->fetchInto( $row, DB_FETCHMODE_ASSOC );
    $this->book_id = $id;
    $this->set_title( $row['title'] );
    $this->set_author( $row['author'] );
    $this->set_publisher( $row['publisher'] );
  }

  function insert()
  {
    global $db;
    $sth = $db->prepare(
'INSERT INTO book ( book_id, title, author, publisher )
   VALUES ( 0, ?, ?, ? )'
    );
    $db->execute( $sth,
      array( $this->get_title(),
        $this->get_author(),
        $this->get_publisher() ) );
    $res = $db->query( "SELECT last_insert_id()" );
    $res->fetchInto( $row );
    return $row[0];
  }

  function update()
  {
    global $db;
    $sth = $db->prepare(
'UPDATE book SET title=?, author=?, publisher=?
  WHERE book_id=?'
    );
    $db->execute( $sth,
      array( $this->get_title(),
        $this->get_author(),
        $this->get_publisher(),
        $this->book_id ) );
  }

  function delete()
  {
    global $db;
    $sth = $db->prepare(
      'DELETE FROM book WHERE book_id=?'
    );
    $db->execute( $sth,
      array( $this->book_id ) );
  }

  function delete_all()
  {
    global $db;
    $sth = $db->prepare( 'DELETE FROM book' );
    $db->execute( $sth );
  }
}

..
Nach dem Login kopieren

To make this change, you have to do two things. First, you must change the fields from individual instance variables to a hash table of field and value pairs. Then you must add a __call method that simply looks at the method name to see whether it was a set_ or a get_ method and set the appropriate field in the hash table.

Note that the load method actually uses the __call method by calling the set_title, set_author, and set_publisher methods -- none of which actually exists.

完全动态化Going completely dynamic


Removing the get_ and set_ methods is just a starting point. To create a completely dynamic database object, you have to give the class the name of the table and the fields, and have no hard-coded references. Listing 5 shows this change.

Listing 5. A completely dynamic database object class
<?php require_once("DB.php");

$dsn = 'mysql://root:password@localhost/bookdb';
$db =& DB::Connect( $dsn, array() );
if (PEAR::isError($db)) { die($db->getMessage()); }

class DBObject
{
  private $id = 0;
  private $table;
  private $fields = array();

  function __construct( $table, $fields )
  {
    $this->table = $table;
    foreach( $fields as $key )
      $this->fields[ $key ] = null;
  }

  function __call( $method, $args )
  {
    if ( preg_match( "/set_(.*)/", $method, $found ) )
    {
      if ( array_key_exists( $found[1], $this->fields ) )
      {
        $this->fields[ $found[1] ] = $args[0];
        return true;
      }
    }
    else if ( preg_match( "/get_(.*)/", $method, $found ) )
    {
      if ( array_key_exists( $found[1], $this->fields ) )
      {
        return $this->fields[ $found[1] ];
      }
    }
    return false;
  }

  function load( $id )
  {
    global $db;
    $res = $db->query(
  "SELECT * FROM ".$this->table." WHERE ".
  $this->table."_id=?",
      array( $id )
    );
    $res->fetchInto( $row, DB_FETCHMODE_ASSOC );
    $this->id = $id;
    foreach( array_keys( $row ) as $key )
      $this->fields[ $key ] = $row[ $key ];
  }

  function insert()
  {
    global $db;

    $fields = $this->table."_id, ";
    $fields .= join( ", ", array_keys( $this->fields ) );

    $inspoints = array( "0" );
    foreach( array_keys( $this->fields ) as $field )
      $inspoints []= "?";
    $inspt = join( ", ", $inspoints );

$sql = "INSERT INTO ".$this->table." ( $fields )
   VALUES ( $inspt )";

    $values = array();
    foreach( array_keys( $this->fields ) as $field )
      $values []= $this->fields[ $field ];

    $sth = $db->prepare( $sql );
    $db->execute( $sth, $values );

    $res = $db->query( "SELECT last_insert_id()" );
    $res->fetchInto( $row );
    $this->id = $row[0];
    return $row[0];
  }

  function update()
  {
    global $db;

    $sets = array();
    $values = array();
    foreach( array_keys( $this->fields ) as $field )
    {
      $sets []= $field.'=?';
      $values []= $this->fields[ $field ];
    }
    $set = join( ", ", $sets );
    $values []= $this->id;

$sql = 'UPDATE '.$this->table.' SET '.$set.
  ' WHERE '.$this->table.'_id=?';

    $sth = $db->prepare( $sql );
    $db->execute( $sth, $values );
  }

  function delete()
  {
    global $db;
    $sth = $db->prepare(
   'DELETE FROM '.$this->table.' WHERE '.
   $this->table.'_id=?'
    );
    $db->execute( $sth,
      array( $this->id ) );
  }

  function delete_all()
  {
    global $db;
    $sth = $db->prepare( 'DELETE FROM '.$this->table );
    $db->execute( $sth );
  }
}

$book = new DBObject( 'book', array( 'author',
   'title', 'publisher' ) );
$book->delete_all();
$book->set_title( "PHP Hacks" );
$book->set_author( "Jack Herrington" );
$book->set_publisher( "O'Reilly" );
$id = $book->insert();

echo ( "New book id = $id\n" );

$book->set_title( "Podcasting Hacks" );
$book->update();

$book2 = new DBObject( 'book', array( 'author',
  'title', 'publisher' ) );
$book2->load( $id );
echo( "Title = ".$book2->get_title()."\n" );
$book2->delete( );
? >
Nach dem Login kopieren

Here, you change the name of the class from Book to DBObject. Then you change the constructor to take the name of the table, as well as the names of the fields in the table. After that, most of the changes happen in the methods of the class, which instead of using some hard-coded Structured Query Language (SQL) now must create the SQL strings on the fly using the table and the field names.

The only assumptions the code makes is that there is a single primary key field and that the name of that field is the name of the table plus _id. So, in the case of the book table, there is a primary key field called book_id. The primary key naming standards you use may be different; if so, you will need to change the code to suit.

This class is much more complex than the original Book class. However, from the perspective of the client of the class, this class is still simple to use. That said, I think the class could be even simpler. In particular, I don't like that I have to specify the name of the table and the fields each time I create a book. If I were to copy and paste this code all around, then change the field structure of the book table, I would be in a bad way. In Listing 6, I solved this problem by creating a simple Book class that inherits from DBObject.

Listing 6. The new Book class

..
class Book extends DBObject
{
  function __construct()
  {
    parent::__construct( 'book',
      array( 'author', 'title', 'publisher' ) );
  }
}

$book = new Book( );
$book->delete_all();
$book->{'title'} = "PHP Hacks";
$book->{'author'} = "Jack Herrington";
$book->{'publisher'} = "O'Reilly";
$id = $book->insert();

echo ( "New book id = $id\n" );

$book->{'title'} = "Podcasting Hacks";
$book->update();

$book2 = new Book( );
$book2->load( $id );
echo( "Title = ".$book2->{'title'}."\n" );
$book2->delete( );
?>
Nach dem Login kopieren

Now, the Book class really is simple. And the client of the Book class no longer needs to know the names of the table or the fields.

还可以改进的地方Room for improvement


One final improvement I want to make on this dynamic class is to use member variables to access the fields, instead of the clunky get_ and set_ operators. Listing 7 shows how to use the __get and __set magic methods instead of __call.

Listing 7. Using the __get and __set methods

<?php require_once("DB.php");

$dsn = 'mysql://root:password@localhost/bookdb';
$db =& DB::Connect( $dsn, array() );
if (PEAR::isError($db)) { die($db->getMessage()); }

class DBObject
{
  private $id = 0;
  private $table;
  private $fields = array();

  function __construct( $table, $fields )
  {
    $this->table = $table;
    foreach( $fields as $key )
      $this->fields[ $key ] = null;
  }

  function __get( $key )
  {
    return $this->fields[ $key ];
  }

  function __set( $key, $value )
  {
    if ( array_key_exists( $key, $this->fields ) )
    {
      $this->fields[ $key ] = $value;
      return true;
    }
    return false;
  }

  function load( $id )
  {
    global $db;
    $res = $db->query(
  "SELECT * FROM ".$this->table." WHERE ".
   $this->table."_id=?",
      array( $id )
    );
    $res->fetchInto( $row, DB_FETCHMODE_ASSOC );
    $this->id = $id;
    foreach( array_keys( $row ) as $key )
      $this->fields[ $key ] = $row[ $key ];
  }

  function insert()
  {
    global $db;

    $fields = $this->table."_id, ";
    $fields .= join( ", ", array_keys( $this->fields ) );

    $inspoints = array( "0" );
    foreach( array_keys( $this->fields ) as $field )
      $inspoints []= "?";
    $inspt = join( ", ", $inspoints );

$sql = "INSERT INTO ".$this->table.
   " ( $fields ) VALUES ( $inspt )";

    $values = array();
    foreach( array_keys( $this->fields ) as $field )
      $values []= $this->fields[ $field ];

    $sth = $db->prepare( $sql );
    $db->execute( $sth, $values );

    $res = $db->query( "SELECT last_insert_id()" );
    $res->fetchInto( $row );
    $this->id = $row[0];
    return $row[0];
  }

  function update()
  {
    global $db;

    $sets = array();
    $values = array();
    foreach( array_keys( $this->fields ) as $field )
    {
      $sets []= $field.'=?';
      $values []= $this->fields[ $field ];
    }
    $set = join( ", ", $sets );
    $values []= $this->id;

$sql = 'UPDATE '.$this->table.' SET '.$set.
  ' WHERE '.$this->table.'_id=?';

    $sth = $db->prepare( $sql );
    $db->execute( $sth, $values );
  }

  function delete()
  {
    global $db;
    $sth = $db->prepare(
'DELETE FROM '.$this->table.' WHERE '.
$this->table.'_id=?'
    );
    $db->execute( $sth,
      array( $this->id ) );
  }

  function delete_all()
  {
    global $db;
    $sth = $db->prepare( 'DELETE FROM '.$this->table );
    $db->execute( $sth );
  }
}

class Book extends DBObject
{
  function __construct()
  {
  parent::__construct( 'book',
    array( 'author', 'title', 'publisher' ) );
  }
}

$book = new Book( );
$book->delete_all();
$book->{'title'} = "PHP Hacks";
$book->{'author'} = "Jack Herrington";
$book->{'publisher'} = "O'Reilly";
$id = $book->insert();

echo ( "New book id = $id\n" );

$book->{'title'} = "Podcasting Hacks";
$book->update();

$book2 = new Book( );
$book2->load( $id );
echo( "Title = ".$book2->{'title'}."\n" );
$book2->delete( );
?>
Nach dem Login kopieren

The test code at the bottom illustrates just how much cleaner this syntax is. To get the title of the book, simply get the title member variable. That variable, in turn, calls the __get method on the object that looks for the title item in the hash table and returns it.

And there you have it: a single dynamic database access class that can bend itself to fit any table in your database.



by iefreer
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn

Heiße KI -Werkzeuge

Undresser.AI Undress

Undresser.AI Undress

KI-gestützte App zum Erstellen realistischer Aktfotos

AI Clothes Remover

AI Clothes Remover

Online-KI-Tool zum Entfernen von Kleidung aus Fotos.

Undress AI Tool

Undress AI Tool

Ausziehbilder kostenlos

Clothoff.io

Clothoff.io

KI-Kleiderentferner

Video Face Swap

Video Face Swap

Tauschen Sie Gesichter in jedem Video mühelos mit unserem völlig kostenlosen KI-Gesichtstausch-Tool aus!

Heiße Werkzeuge

Notepad++7.3.1

Notepad++7.3.1

Einfach zu bedienender und kostenloser Code-Editor

SublimeText3 chinesische Version

SublimeText3 chinesische Version

Chinesische Version, sehr einfach zu bedienen

Senden Sie Studio 13.0.1

Senden Sie Studio 13.0.1

Leistungsstarke integrierte PHP-Entwicklungsumgebung

Dreamweaver CS6

Dreamweaver CS6

Visuelle Webentwicklungstools

SublimeText3 Mac-Version

SublimeText3 Mac-Version

Codebearbeitungssoftware auf Gottesniveau (SublimeText3)

PHP 8.4 Installations- und Upgrade-Anleitung für Ubuntu und Debian PHP 8.4 Installations- und Upgrade-Anleitung für Ubuntu und Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 bringt mehrere neue Funktionen, Sicherheitsverbesserungen und Leistungsverbesserungen mit einer beträchtlichen Menge an veralteten und entfernten Funktionen. In dieser Anleitung wird erklärt, wie Sie PHP 8.4 installieren oder auf PHP 8.4 auf Ubuntu, Debian oder deren Derivaten aktualisieren. Obwohl es möglich ist, PHP aus dem Quellcode zu kompilieren, ist die Installation aus einem APT-Repository wie unten erläutert oft schneller und sicherer, da diese Repositorys in Zukunft die neuesten Fehlerbehebungen und Sicherheitsupdates bereitstellen.

7 PHP-Funktionen, die ich leider vorher nicht kannte 7 PHP-Funktionen, die ich leider vorher nicht kannte Nov 13, 2024 am 09:42 AM

Wenn Sie ein erfahrener PHP-Entwickler sind, haben Sie möglicherweise das Gefühl, dass Sie dort waren und dies bereits getan haben. Sie haben eine beträchtliche Anzahl von Anwendungen entwickelt, Millionen von Codezeilen debuggt und eine Reihe von Skripten optimiert, um op zu erreichen

So richten Sie Visual Studio-Code (VS-Code) für die PHP-Entwicklung ein So richten Sie Visual Studio-Code (VS-Code) für die PHP-Entwicklung ein Dec 20, 2024 am 11:31 AM

Visual Studio Code, auch bekannt als VS Code, ist ein kostenloser Quellcode-Editor – oder eine integrierte Entwicklungsumgebung (IDE) –, die für alle gängigen Betriebssysteme verfügbar ist. Mit einer großen Sammlung von Erweiterungen für viele Programmiersprachen kann VS Code c

Erklären Sie JSON Web Tokens (JWT) und ihren Anwendungsfall in PHP -APIs. Erklären Sie JSON Web Tokens (JWT) und ihren Anwendungsfall in PHP -APIs. Apr 05, 2025 am 12:04 AM

JWT ist ein offener Standard, der auf JSON basiert und zur sicheren Übertragung von Informationen zwischen Parteien verwendet wird, hauptsächlich für die Identitätsauthentifizierung und den Informationsaustausch. 1. JWT besteht aus drei Teilen: Header, Nutzlast und Signatur. 2. Das Arbeitsprinzip von JWT enthält drei Schritte: Generierung von JWT, Überprüfung von JWT und Parsingnayload. 3. Bei Verwendung von JWT zur Authentifizierung in PHP kann JWT generiert und überprüft werden, und die Funktionen und Berechtigungsinformationen der Benutzer können in die erweiterte Verwendung aufgenommen werden. 4. Häufige Fehler sind Signaturüberprüfungsfehler, Token -Ablauf und übergroße Nutzlast. Zu Debugging -Fähigkeiten gehört die Verwendung von Debugging -Tools und Protokollierung. 5. Leistungsoptimierung und Best Practices umfassen die Verwendung geeigneter Signaturalgorithmen, das Einstellen von Gültigkeitsperioden angemessen.

Wie analysiert und verarbeitet man HTML/XML in PHP? Wie analysiert und verarbeitet man HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

Dieses Tutorial zeigt, wie XML -Dokumente mit PHP effizient verarbeitet werden. XML (Extensible Markup-Sprache) ist eine vielseitige textbasierte Markup-Sprache, die sowohl für die Lesbarkeit des Menschen als auch für die Analyse von Maschinen entwickelt wurde. Es wird üblicherweise für die Datenspeicherung ein verwendet und wird häufig verwendet

PHP -Programm zum Zählen von Vokalen in einer Zeichenfolge PHP -Programm zum Zählen von Vokalen in einer Zeichenfolge Feb 07, 2025 pm 12:12 PM

Eine Zeichenfolge ist eine Folge von Zeichen, einschließlich Buchstaben, Zahlen und Symbolen. In diesem Tutorial wird lernen, wie Sie die Anzahl der Vokale in einer bestimmten Zeichenfolge in PHP unter Verwendung verschiedener Methoden berechnen. Die Vokale auf Englisch sind a, e, i, o, u und sie können Großbuchstaben oder Kleinbuchstaben sein. Was ist ein Vokal? Vokale sind alphabetische Zeichen, die eine spezifische Aussprache darstellen. Es gibt fünf Vokale in Englisch, einschließlich Großbuchstaben und Kleinbuchstaben: a, e, ich, o, u Beispiel 1 Eingabe: String = "TutorialPoint" Ausgabe: 6 erklären Die Vokale in der String "TutorialPoint" sind u, o, i, a, o, ich. Insgesamt gibt es 6 Yuan

Erklären Sie die späte statische Bindung in PHP (statisch: :). Erklären Sie die späte statische Bindung in PHP (statisch: :). Apr 03, 2025 am 12:04 AM

Statische Bindung (statisch: :) implementiert die späte statische Bindung (LSB) in PHP, sodass das Aufrufen von Klassen in statischen Kontexten anstatt Klassen zu definieren. 1) Der Analyseprozess wird zur Laufzeit durchgeführt.

Was sind PHP Magic -Methoden (__construct, __Destruct, __call, __get, __set usw.) und geben Sie Anwendungsfälle an? Was sind PHP Magic -Methoden (__construct, __Destruct, __call, __get, __set usw.) und geben Sie Anwendungsfälle an? Apr 03, 2025 am 12:03 AM

Was sind die magischen Methoden von PHP? Zu den magischen Methoden von PHP gehören: 1. \ _ \ _ Konstrukt, verwendet, um Objekte zu initialisieren; 2. \ _ \ _ Destruct, verwendet zur Reinigung von Ressourcen; 3. \ _ \ _ Call, behandeln Sie nicht existierende Methodenaufrufe; 4. \ _ \ _ GET, Implementieren Sie den dynamischen Attributzugriff; 5. \ _ \ _ Setzen Sie dynamische Attributeinstellungen. Diese Methoden werden in bestimmten Situationen automatisch aufgerufen, wodurch die Code -Flexibilität und -Effizienz verbessert werden.

See all articles