gpt4 book ai didi

php - 从 ajax 文件访问以前包含的(必需的)类方法

转载 作者:行者123 更新时间:2023-12-04 06:08:53 26 4
gpt4 key购买 nike

我是 php 新手,我想知道从面向前端的 ajax 文件中使用以前定义的类方法的最佳方法。我在 50 个或更多的热门问题中寻找与此类似的问题,所以如果之前有人问过这个问题,我深表歉意。

我的项目是使用一个调用 initialize.php 的前端 Controller 设置的,它包含我迄今为止为这个项目制作的所有类文件,无论现在是否需要这些类方法/属性(如果这非常糟糕)那么有人请告诉我另一种选择:[[)。所以基本上,对于在这个站点上发出的每个请求,调用 initialize ,所有这些类都被定义,两个类被立即实例化,这两个类是我用于数据库和 session /登录内容的类。

我一直在我的 ajax 文件中这样做:

<?php
// login.ajax.php
require_once 'initialize.php';

$email = $_POST['email'];
$password = $_POST['password'];
$remember = $_POST['remember'];

global $session; // this is instantiated right away every time
$login = $session->login($email, $password);

echo json_encode($login);
?>

最近的并发症现在让我重新考虑这种方法。不断加载 initialize 似乎真的很浪费,但是只包含/需要必要的类文件充其量只是一种痛苦。在这个例子中,我需要包含 session,它也需要另外两个类来执行这个登录。

最佳答案

看来你不妨用 PHP 自动加载机制 .
详情请至the PHP autoloading documentation .你可以在那里读到:

Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).

In PHP 5, this is no longer necessary. You may define an __autoload function which is automatically called in case you are trying to use a class/interface which hasn't been defined yet. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.


在您的初始化文件(或单独的文件,取决于您的设计决策)中,只需定义 __autoload()将用于包含所需文件的函数:
function __autoload($class_name) {
include_once $class_name . '.php';
}
这应该解决多个需求/包含声明的问题/需要 - 从现在开始,当您实例化某个类并且它不可用时,将调用新定义的函数( __autoload() )以包含必要的文件。

关于php - 从 ajax 文件访问以前包含的(必需的)类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8017799/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com