목차
动态特性的重要性The importance of being dynamic
写一个柔性类Writing a bendy class
传统的数据库访问方式Classic database access
引入一点动态A little dab of dynamic
完全动态化Going completely dynamic
还可以改进的地方Room for improvement
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( );
?>
로그인 후 복사

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 );
  }
}

..
로그인 후 복사

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( );
? >
로그인 후 복사

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( );
?>
로그인 후 복사

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( );
?>
로그인 후 복사

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
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드 Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드 Dec 24, 2024 pm 04:42 PM

PHP 8.4는 상당한 양의 기능 중단 및 제거를 통해 몇 가지 새로운 기능, 보안 개선 및 성능 개선을 제공합니다. 이 가이드에서는 Ubuntu, Debian 또는 해당 파생 제품에서 PHP 8.4를 설치하거나 PHP 8.4로 업그레이드하는 방법을 설명합니다.

이전에 몰랐던 후회되는 PHP 함수 7가지 이전에 몰랐던 후회되는 PHP 함수 7가지 Nov 13, 2024 am 09:42 AM

숙련된 PHP 개발자라면 이미 그런 일을 해왔다는 느낌을 받을 것입니다. 귀하는 상당한 수의 애플리케이션을 개발하고, 수백만 줄의 코드를 디버깅하고, 여러 스크립트를 수정하여 작업을 수행했습니다.

PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법 PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법 Dec 20, 2024 am 11:31 AM

VS Code라고도 알려진 Visual Studio Code는 모든 주요 운영 체제에서 사용할 수 있는 무료 소스 코드 편집기 또는 통합 개발 환경(IDE)입니다. 다양한 프로그래밍 언어에 대한 대규모 확장 모음을 통해 VS Code는

JWT (JSON Web Tokens) 및 PHP API의 사용 사례를 설명하십시오. JWT (JSON Web Tokens) 및 PHP API의 사용 사례를 설명하십시오. Apr 05, 2025 am 12:04 AM

JWT는 주로 신분증 인증 및 정보 교환을 위해 당사자간에 정보를 안전하게 전송하는 데 사용되는 JSON을 기반으로 한 개방형 표준입니다. 1. JWT는 헤더, 페이로드 및 서명의 세 부분으로 구성됩니다. 2. JWT의 작업 원칙에는 세 가지 단계가 포함됩니다. JWT 생성, JWT 확인 및 Parsing Payload. 3. PHP에서 인증에 JWT를 사용하면 JWT를 생성하고 확인할 수 있으며 사용자 역할 및 권한 정보가 고급 사용에 포함될 수 있습니다. 4. 일반적인 오류에는 서명 검증 실패, 토큰 만료 및 대형 페이로드가 포함됩니다. 디버깅 기술에는 디버깅 도구 및 로깅 사용이 포함됩니다. 5. 성능 최적화 및 모범 사례에는 적절한 시그니처 알고리즘 사용, 타당성 기간 설정 합리적,

PHP에서 HTML/XML을 어떻게 구문 분석하고 처리합니까? PHP에서 HTML/XML을 어떻게 구문 분석하고 처리합니까? Feb 07, 2025 am 11:57 AM

이 튜토리얼은 PHP를 사용하여 XML 문서를 효율적으로 처리하는 방법을 보여줍니다. XML (Extensible Markup Language)은 인간의 가독성과 기계 구문 분석을 위해 설계된 다목적 텍스트 기반 마크 업 언어입니다. 일반적으로 데이터 저장 AN에 사용됩니다

문자열로 모음을 계산하는 PHP 프로그램 문자열로 모음을 계산하는 PHP 프로그램 Feb 07, 2025 pm 12:12 PM

문자열은 문자, 숫자 및 기호를 포함하여 일련의 문자입니다. 이 튜토리얼은 다른 방법을 사용하여 PHP의 주어진 문자열의 모음 수를 계산하는 방법을 배웁니다. 영어의 모음은 A, E, I, O, U이며 대문자 또는 소문자 일 수 있습니다. 모음이란 무엇입니까? 모음은 특정 발음을 나타내는 알파벳 문자입니다. 대문자와 소문자를 포함하여 영어에는 5 개의 모음이 있습니다. a, e, i, o, u 예 1 입력 : String = "Tutorialspoint" 출력 : 6 설명하다 문자열의 "Tutorialspoint"의 모음은 u, o, i, a, o, i입니다. 총 6 개의 위안이 있습니다

PHP에서 늦은 정적 결합을 설명하십시오 (정적 : :). PHP에서 늦은 정적 결합을 설명하십시오 (정적 : :). Apr 03, 2025 am 12:04 AM

정적 바인딩 (정적 : :)는 PHP에서 늦은 정적 바인딩 (LSB)을 구현하여 클래스를 정의하는 대신 정적 컨텍스트에서 호출 클래스를 참조 할 수 있습니다. 1) 구문 분석 프로세스는 런타임에 수행됩니다. 2) 상속 관계에서 통화 클래스를 찾아보십시오. 3) 성능 오버 헤드를 가져올 수 있습니다.

php magic 방법 (__construct, __destruct, __call, __get, __set 등)이란 무엇이며 사용 사례를 제공합니까? php magic 방법 (__construct, __destruct, __call, __get, __set 등)이란 무엇이며 사용 사례를 제공합니까? Apr 03, 2025 am 12:03 AM

PHP의 마법 방법은 무엇입니까? PHP의 마법 방법은 다음과 같습니다. 1. \ _ \ _ Construct, 객체를 초기화하는 데 사용됩니다. 2. \ _ \ _ 파괴, 자원을 정리하는 데 사용됩니다. 3. \ _ \ _ 호출, 존재하지 않는 메소드 호출을 처리하십시오. 4. \ _ \ _ get, 동적 속성 액세스를 구현하십시오. 5. \ _ \ _ Set, 동적 속성 설정을 구현하십시오. 이러한 방법은 특정 상황에서 자동으로 호출되어 코드 유연성과 효율성을 향상시킵니다.

See all articles