search
HomeBackend DevelopmentPHP TutorialPHP的学习-可变函数

PHP的学习--可变函数

PHP 支持可变函数的概念。这意味着如果一个变量名后有圆括号,PHP 将寻找与变量的值同名的函数,并且尝试执行它。可变函数可以用来实现包括回调函数,函数表在内的一些用途。

可变函数不能用于例如 echo,print,unset(),isset(),empty(),include,require 以及类似的语言结构。需要使用自己的包装函数来将这些结构用作可变函数。

 

Example #1 可变函数示例

<span style="color: #000000;">php</span><span style="color: #0000ff;">function</span><span style="color: #000000;"> foo() {    </span><span style="color: #0000ff;">echo</span> "In foo()<br>\n"<span style="color: #000000;">;}</span><span style="color: #0000ff;">function</span> bar(<span style="color: #800080;">$arg</span> = ''<span style="color: #000000;">) {    </span><span style="color: #0000ff;">echo</span> "In bar(); argument was '<span style="color: #800080;">$arg</span>'.<br>\n"<span style="color: #000000;">;}</span><span style="color: #008000;">//</span><span style="color: #008000;"> 使用 echo 的包装函数</span><span style="color: #0000ff;">function</span> echoit(<span style="color: #800080;">$string</span><span style="color: #000000;">){    </span><span style="color: #0000ff;">echo</span> <span style="color: #800080;">$string</span><span style="color: #000000;">;}</span><span style="color: #800080;">$func</span> = 'foo'<span style="color: #000000;">;</span><span style="color: #800080;">$func</span>();        <span style="color: #008000;">//</span><span style="color: #008000;"> This calls foo()</span><span style="color: #800080;">$func</span> = 'bar'<span style="color: #000000;">;</span><span style="color: #800080;">$func</span>('test');  <span style="color: #008000;">//</span><span style="color: #008000;"> This calls bar()</span><span style="color: #800080;">$func</span> = 'echoit'<span style="color: #000000;">;</span><span style="color: #800080;">$func</span>('test');  <span style="color: #008000;">//</span><span style="color: #008000;"> This calls echoit()</span>?>

也可以用可变函数的语法来调用一个对象的方法。

<span style="color: #000000;">php</span><span style="color: #0000ff;">class</span><span style="color: #000000;"> Foo{    </span><span style="color: #0000ff;">function</span><span style="color: #000000;"> Variable()    {        </span><span style="color: #800080;">$name</span> = 'Bar'<span style="color: #000000;">;        </span><span style="color: #800080;">$this</span>-><span style="color: #800080;">$name</span>(); <span style="color: #008000;">//</span><span style="color: #008000;"> This calls the Bar() method</span><span style="color: #000000;">    }    </span><span style="color: #0000ff;">function</span><span style="color: #000000;"> Bar()    {        </span><span style="color: #0000ff;">echo</span> "This is Bar"<span style="color: #000000;">;    }}</span><span style="color: #800080;">$foo</span> = <span style="color: #0000ff;">new</span><span style="color: #000000;"> Foo();</span><span style="color: #800080;">$funcname</span> = "Variable"<span style="color: #000000;">;</span><span style="color: #800080;">$foo</span>-><span style="color: #800080;">$funcname</span>();   <span style="color: #008000;">//</span><span style="color: #008000;"> This calls $foo->Variable()</span>?>

当调用静态方法时,函数调用要比静态属性优先:

Example #3 Variable 方法和静态属性示例

<span style="color: #000000;">php</span><span style="color: #0000ff;">class</span><span style="color: #000000;"> Foo{    </span><span style="color: #0000ff;">static</span> <span style="color: #800080;">$variable</span> = 'static property'<span style="color: #000000;">;    </span><span style="color: #0000ff;">static</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> Variable()    {        </span><span style="color: #0000ff;">echo</span> 'Method Variable called'<span style="color: #000000;">;    }}</span><span style="color: #0000ff;">echo</span> Foo::<span style="color: #800080;">$variable</span>; <span style="color: #008000;">//</span><span style="color: #008000;"> This prints 'static property'. It does need a $variable in this scope.</span><span style="color: #800080;">$variable</span> = "Variable"<span style="color: #000000;">;Foo</span>::<span style="color: #800080;">$variable</span>();  <span style="color: #008000;">//</span><span style="color: #008000;"> This calls $foo->Variable() reading $variable in this scope.</span>?>

可以使用可变函数的方法列表如下:

<span style="color: #000000;">php</span><span style="color: #008080;">array_diff_assoc</span><span style="color: #000000;">()array_diff_key()</span><span style="color: #008080;">array_diff_uassoc</span><span style="color: #000000;">()</span><span style="color: #0000ff;">array</span><span style="color: #000000;">()array_intersect_ukey()</span><span style="color: #008080;">array_map</span><span style="color: #000000;">()</span><span style="color: #008080;">array_merge</span><span style="color: #000000;">()</span><span style="color: #008080;">array_merge_recursive</span><span style="color: #000000;">()</span><span style="color: #008080;">array_multisort</span><span style="color: #000000;">()</span><span style="color: #008080;">array_push</span><span style="color: #000000;">()array_replace()array_replace_recursive()</span><span style="color: #008080;">array_unshift</span><span style="color: #000000;">()</span><span style="color: #008080;">call_user_func</span><span style="color: #000000;">()</span><span style="color: #008080;">call_user_method</span><span style="color: #000000;">()</span><span style="color: #008080;">compact</span><span style="color: #000000;">()dba_open()dba_popen()</span><span style="color: #0000ff;">echo</span><span style="color: #000000;">()forward_static_call()</span><span style="color: #008080;">fprintf</span><span style="color: #000000;">()</span><span style="color: #008080;">fscanf</span><span style="color: #000000;">()httprequestpool_construct()ibase_execute()ibase_set_event_handler()ibase_wait_event()</span><span style="color: #0000ff;">isset</span><span style="color: #000000;">()</span><span style="color: #0000ff;">list</span><span style="color: #000000;">()maxdb_stmt_bind_param()maxdb_stmt_bind_result()mb_convert_variables()newt_checkbox_tree_add_item()newt_grid_h_close_stacked()newt_grid_h_stacked()newt_grid_v_close_stacked()newt_grid_v_stacked()newt_win_choice()newt_win_entries()newt_win_menu()newt_win_message()newt_win_ternary()</span><span style="color: #008080;">pack</span><span style="color: #000000;">()</span><span style="color: #008080;">printf</span><span style="color: #000000;">()</span><span style="color: #008080;">register_shutdown_function</span><span style="color: #000000;">()</span><span style="color: #008080;">register_tick_function</span><span style="color: #000000;">()</span><span style="color: #008080;">session_register</span><span style="color: #000000;">()</span><span style="color: #008080;">setlocale</span><span style="color: #000000;">()</span><span style="color: #008080;">sprintf</span><span style="color: #000000;">()</span><span style="color: #008080;">sscanf</span><span style="color: #000000;">()</span><span style="color: #0000ff;">unset</span><span style="color: #000000;">()</span><span style="color: #008080;">var_dump</span><span style="color: #000000;">()w32api_deftype()w32api_init_dtype()w32api_invoke_function()</span><span style="color: #008080;">wddx_add_vars</span><span style="color: #000000;">()</span><span style="color: #008080;">wddx_serialize_vars</span>()

 

摘自:http://php.net/manual/zh/functions.variable-functions.php

 

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 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

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor