douping3860 2012-11-16 02:50
浏览 113
已采纳

如何从网页上的函数中调用php类的函数

Code example;

PHP Web Page: (index.php)

 <html><head></head>
    <body>
    <?php 
    include("class_validation.php");
    $val = new validation();

        if(isset($_POST['action'])) doSomething();

    function doSomething() {
        $val->validate(); //I AM UNABLE TO DO THIS!
    }
    ?>
    </body>
    </html>

PHP file: (class_validation.php)

<?php
class validation()
{
    function validate(){
        //some validation
    }
}
?>

QUESTION: How can I call a function from the 'class_validation.php' file in a function I created in my PHP web page? I can correctly call the function doSomething() as well as call the function $val->validate(); when not located in another function. I there a way to do this?

  • 写回答

2条回答 默认 最新

  • douya2982 2012-11-16 02:52
    关注

    $val is out of scope in that doSomething() function call. Pass it as a parameter to the function:

    // Define the function to accept a parameter. Use a type hint to be sure it is 
    // a validation object
    function doSomething(validation $val) {
      $val->validate(); 
    }
    
    if(isset($_POST['action'])) doSomething($val);
    

    (PHP documentation on type hinting)

    Alternatively, and not recommended, you may use the global keyword inside the function to reference the global $val.

    function doSomething() {
      // Don't do it this way. The func parameter is preferred
      global $val;
      $val->validate(); 
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器