Home php教程 php手册 php中的动态调用实例分析

php中的动态调用实例分析

Jun 06, 2016 pm 08:14 PM
php dynamic transfer

这篇文章主要介绍了php中的动态调用的使用技巧,实例分析了动态调用的具体用法与注意事项,需要的朋友可以参考下

本文实例讲述了php中的动态调用具体用法。分享给大家供大家参考。具体分析如下:

在程序中如果加一大堆判断的确是一个很大的麻烦,例如这样:

复制代码 代码如下:

if($fun='a'){echo "哎呀!";}
elesif(){}
……
else{echo "嗯!";}


真的很麻烦并且造成程序后期阅读和修改时候的巨大麻烦,这时候我们可以把每一个要执行的代码段,用函数来实现,然后可以用一个更加NB的方法来实现这些功能,并且因为每一个函数实现一个功能,我们维护起来就简单多了.

进入正题,看看PHP动态调用函数到底有什么作用,在PHP中是可以动态调用函数的,像这样$fun(),PHP解析器可以根据变量$fun的值来调用对用的函数,,例如$fun='a',解析器看到的将是a();这样的形式,从而调用函数a,具体代码如下:

复制代码 代码如下:

//controller.php
(isset($_GET['fun'])&&$_GET['fun']!='')?$fun=$_GET['fun']:$fun='def';
 
controller($fun);
 
function controller($fun){
     if(function_exists($fun)) $fun();
     else echo "函数{$fun}未定义";
}
 
function def(){
     echo "由于用户没有传递参数,调用了缺省的函数def()";
}
function a(){
    echo "函数a被调用!";
}
function b(){
    echo "函数b被调用!";
}
?>


实例代码如下:

复制代码 代码如下:

 require_once showErrMsg.php;
 $_action = (isset($_REQUEST[action])?$_REQUEST[action]:"");
 if($_action!=null&&$_action!=){
  if(function_exists($_action)){
   eval("$_action();");
  }else{
   die(showErrMsg ( "
当前php文件中不存在方法[".$_action."()]。"));
  }
 }
?>
 
function showErrMsg($strMsg){
  return "".$strMsg."";
 }
?>


在前台页面我们可以用不同的链接来实现不同的功能,例如我们有这样一个链接

?fun=a

当请求到达controller.php的时候,PHP程序将会自动的执行函数a().

问题的重点:

在于我们在这个程序的页面首先调用了controller()函数。这个函数首先判断参数中定义的函数名称($fun的值)是否被定义,如果定义了就调用这个函数。

如果在$_GET参数中fun没有定义:

就调用一个缺省的函数def();

这样的代码是不是简洁很对呢?你可以把这些代码拷贝回去,自己看看效果——我肯定的告诉你,这些代码运行时正常的!

然而我也很不幸的告诉你:其实这段看起来整齐的代码有一个巨大的安全隐患在里面,很大,很大的安全隐患,具体是啥,感兴趣的朋友可以参考相关文档,相信你肯定不会把这一段代码立马用到服务器上的?

另外经过测试证实,这个方法不但可以动态调用函数,并且也可以动态实例化对象,像这样:

复制代码 代码如下:

$obj = new $obj();

代码如下:

复制代码 代码如下:

class A
{
      function foo()
      {
          if (isset($this)) {
              echo '$this is defined (';
              echo get_class($this);
              echo ")n";
          } else {
              echo "$this is not defined.n";
          }
      }
}
 
class B
{
      function bar()
      {
        A::foo();
         //parent::foo();
      }
}
 
$a = new A();
$a->foo();//动态调用,因为new了对象
A::foo();//静态调用,直接用类名去调用,没有new对象
$b = new B();
$b->bar();//在对象$b中,A::foo();进行静态调用
B::bar();
?>


总结:静态、动态调用都指类、对象对其方法的调用,动态指的是创建(new)了对象,然后用对象变量去调用方法;静态则是没有创建对象,直接用类名去调用,至于另一个对象那就很简单了,不同的类创建不同的对象,比如class A;class B ,$a = new A();$b = new B();$a and $b 相对之间就是另一个对象了.

希望本文所述对大家的php程序设计有所帮助。

Statement of this Website
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

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1676
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

See all articles