简体   繁体   English

在 PHP 中,我可以在类中的函数内使用和包含或要求吗?

[英]In PHP, can I use and Include or Require inside a Function within a Class?

We are changing old PHP/MySQL code to new MySQLi OOP code and it would be easier to INCLUDE the new code in the same location in the existing code.我们正在将旧的 PHP/MySQL 代码更改为新的 MySQLi OOP 代码,并且将新代码包含在现有代码的相同位置会更容易。 However, some of the code resides as a Function inside a Class and I am not sure if I can just plug in the include.但是,有些代码作为函数驻留在类中,我不确定是否可以插入包含。

For example, the old code is:例如,旧代码是:

class get_names
    {
      function __construct()
         {
            $temp = mysql_query("select first_name last_name from name_table
                    where member_id=".$_SESSION['member_id']);
            $names = mysql_fetch_array($temp);
          }
     }

Changed to:变成:

class get_names
    {
       function __construct()
          {
             include("GetNames.php");
          }
     }

Can this be done in this fashion?这可以以这种方式完成吗? Thanks for your help.谢谢你的帮助。

You should rather autoload your classes and use FQNS (Fully Qualified Name Space).您应该自动加载您的类并使用FQNS (完全限定名称空间)。 This way you don't need to be checking what files you should include each time.这样您就不需要每次都检查应该包含哪些文件。

Can you?你是否可以? Yes.是的。

Should you?你应该? No. This is not a good style and will be harder to maintain.不。这不是一个好的样式,并且会更难维护。 A better solution would be to write a function in a separate file, include that file, and call the function.更好的解决方案是在单独的文件中编写一个函数,包含该文件,然后调用该函数。

GetNames.php:获取名称.php:

function getNames()
{
    $temp = mysql_query("select first_name last_name from name_table
            where member_id=" . mysql_real_escape_string($_SESSION['member_id']));
    return mysql_fetch_array($temp);
}

Class file:类文件:

require_once 'GetNames.php';

class get_names
{
   function __construct()
      {
         $names = getNames();
      }
 }

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

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