繁体   English   中英

如何使用php调用单独的函数文件?

[英]How to call the separate functions file using php?

好的,所以我只是在学习使用php编程,而且似乎所有教程都没有提到有关具有functions.php文件和单独的db_connect.php文件的内容。 我需要帮助,因此我正在尝试建立学生管理系统。 我进行了登录和注销,它们正常工作,并且个人资料页面显示了用户名。 但是现在,例如,当我想查看所提供的所有课程时,如何从一个单独的文件中查看呢? 并在profile.php文件中调用它。

functions.php类:

<?php


    class Functions{
            private $link;

            public function __construct(){
                //require_once dirname(__FILE__) returns the path of the current directory


                global $link;
                $this->link = $link;
            }

            public function viewAllCourses(){
             $stmt = $this->link->prepare("SELECT * FROM courses where active = 1");
                    $stmt->execute();
                    $stmt->fetch();


                $stmt->store_result(); 
                if($stmt->num_rows > 0){
                    while($row = $stmt->fetch_assoc()){
                        echo $row['course_num'] . "<br>";
                        echo $row['professor_teaching'] . "<br>";
                        echo $row['name'] . "<br>";
                    }
                }
            }
    }
?>

然后这是我尝试在profile.php文件中调用的段:

<?php
    require('functions.php');
    $functions = new Functions();

    echo $functions->viewAllCourses();
?>

我希望它打印课程,但我排名第n。 我究竟做错了什么?

通常,将数据库连接对象作为参数添加到Function类的构造函数中,而不是像您那样使用global调用,因此可以像下面这样重写Functions类:

<?php

    class Functions{
        private $link;

        public function __construct( $link ){
            $this->link = $link;
        }

        public function viewAllCourses(){

            $sql='select * from `courses` where `active` = 1';
            $res = $this->link->query( $sql );

            if( $res ){
                while( $rs=$res->fetch_object() ){
                    printf(
                        '%s<br />%s<br />%s<br />',
                        $rs->course_num,
                        $rs->professor_teaching,
                        $rs->name
                    )
                }
                return true;
            }
            return false;
        }

    } //end class
?>

viewAllCourses方法不需要准备好的语句,因为没有使用用户提供的数据,因此在运行时无法篡改sql,因此简单query就足够了。

叫课

<?php
    /* include the necessary files */
    require 'db_connect.php';
    require 'functions.php';

    /* construct the db connection to supply as an argument to the Functions class */
    $db=new db_connect();

    /* invoke the functions class */
    $fn = new Functions( $db );

    /* the `viewAllCourses` method echoes the output */
    $fn->viewAllCourses();
?>

只需在$ functions-> viewAllCourses()之前删除回显即可;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM