search
HomeBackend DevelopmentPHP Tutorial PHP幻术方法小结1

PHP魔术方法小结1
PHP中除了有大量的魔术变量外,还有很多_开头的魔术方法,本文简单小结下:

1 _construct 和_destruct就不说了,构造和析构.

2 _call和_callStatic
  例子:
    class myClass() {
    private $a = true;
  }

  $myObj = new myClass();
  $myObj->showValue();

  ?>
   这里会说出错,那当然的,没定义.可以用
  class Greetings {
    function __call( $functionName, $argumentsArray ) {
      echo "Hello, " . ucfirst( $functionName ) . " !!!";
    }
  }
  $sayHello = new Greetings();
_CALL会在调用没有定义任何方法时触发

还有_callStatic
  class Greetings {
    static function __callStatic( $functionName, $argumentsArray ) {
      echo "Hello, " . ucfirst( $functionName ) . " !!!";
    }
  }

  Greetings::steve();
 

3 _set和_get
   这个是强制在类中声明的变量才能被使用,一个例子:
class myClass {
private $onlyDataMember = 0;
}
$classObj = new myClass();
$classObj->undefinedDataMember = 'Some Value';
echo $classObj->undefinedDataMember;
?>
  这个是直接输出了没定义的值,不大好,可以改成这样,强制性地:
class myClass {
private $onlyDataMember = 0;

function __set( $dataMemberName, $dataMemberValue ) {
throw new Exception( "Object property $dataMemberName is not writable!" );
}

function __get( $dataMemberName ) {
throw new Exception( "Object property $dataMemberName is not defined!" );
}
}

再来一个例子:
class UserInfo2{

   private $aData = array();

}

$oUserInfo2 = new UserInfo2;

$oUserInfo2->aData['UserName'] = '木目子';

$oUserInfo2->aData['PassWord'] = '123456';

$oUserInfo2->aData['Birthdat'] = '1978-08-16';

echo "用户名:".$oUserInfo2->aData['UserName'] ."
\n";

echo "密   码:".$oUserInfo2->aData['PassWord'] ."
\n";

echo "生   日:".$oUserInfo2->aData['Birthday'] ."
\n";

显然,这段代码会出错的,因为aData是UserInfo的私有属性,不能直接在外部使用,那现在问题是必须要给aData进行付值,这个时候__set和__get就排上用场了:

class UserInfo3{

   //private $aData = array();

   private $aData = array();

   function __set($property,$value){

     $this->aData[$property] = $value;

   }

   function __get($property){

     return $this->aData[$property];

   }

}

$oUserInfo3 = new UserInfo3;

$oUserInfo3->aData['UserName'] = '木目子';

$oUserInfo3->aData['PassWord'] = '123456';

$oUserInfo3->aData['Birthdat'] = '1978-08-16';

echo "用户名:".$oUserInfo3->aData['UserName'] ."
\n";

echo "密   码:".$oUserInfo3->aData['PassWord'] ."
\n";

echo "生   日:".$oUserInfo3->aData['Birthday'] ."
\n";




$classObj = new myClass();
$classObj->undefinedDataMember = 'Some Value';
echo $classObj->undefinedDataMember;

?>
  这样当调用的时候,就强制报错了

4) _invoke
  把对象当函数用,典型的例子为,平常我们一般这样用:
class myDbUsersClass {
private $recordsArray = array();

function __construct( $fetchThisMuchUsers ) {
// code for fetching $fetchThisMuchUsers number of records from database and store them to $recordsArray.
}

function getUsers() {
return $recordsArray;
}
}

$classObj = new myDbUsersClass( 10 );
$users = $classObj->getUsers();
foreach( $users as $user ) {
echo $user[ 'userName' ] . '
';
}
?>
现在可以这样用:
class myDbUsersClass {
private $recordsArray = array();

function __construct( $fetchThisMuchUsers ) {
// code for fetching $fetchThisMuchUsers number of records from database and store them to $recordsArray.
}

function __invoke( $onlyArgumentItAccepts ) {
return $recordsArray;
}
}

$classObj = new myDbUsersClass( 10 );
foreach( $classObj() as $user ) {
echo $user[ 'userName' ] . '
';
}
?>
 

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.