Class not found in the same file [duplicate]

假装没事ソ 提交于 2020-01-01 16:43:13

问题


Possible Duplicate:
Derived class defined later in the same file “does not exist”?

Does anyone has the slighties idea why I'm getting a Fatal Error: Class 'PublicacionController' not found when trying to initialize it in the if statement below ?

--PublicacionController.php--
<?php
/*Some random includes, those are 
right as far as Im concerned*/

//AJAX call
if(!empty($_POST)){
    if($_POST['call']=='nuevaPublicacion'){
        $pc = new PublicacionController();
        $pc->nuevaPublicacion($_POST);
        exit;
    }
}

class PublicacionController extends Controller{/* STUFF*/}
?>

It is a single file. Im calling the controller from an AJAX call (dunno if it has something to do with).

I'm running a standard Amazon Ec2 instance, with Amazon Linux and the default https and PHP versions from the repos (the same Fedora uses I think).


回答1:


PHP classes should be defined before instantiation, see the "new" section of the PHP OO documentation.

An easy way to achieve that is by first declaring the classes and then the main code:

--PublicacionController.php--
<?php
/*Some random includes, those are 
right as far as I'm concerned*/

class PublicacionController extends Controller{/* STUFF*/}

//AJAX call
if(!empty($_POST)){
    if($_POST['call']=='nuevaPublicacion'){
        $pc = new PublicacionController();
        $pc->nuevaPublicacion($_POST);
        exit;
    }
}

?>



回答2:


This is a PHP ERROR see : Derived class defined later in the same file "does not exist"?

If you run

if (! empty($_POST)) {
    if ($_POST['call'] == 'nuevaPublicacion') {
        $pc = new PublicacionController();
        $pc->nuevaPublicacion($_POST);
        exit();
    }
}

class Controller {
    function nuevaPublicacion($array) {
    }
}
class PublicacionController extends Controller {/* STUFF*/

The code above would work fine be the moment Controller is included via external file it would begin to generate error.

Advice declare all your classes before you use them for now especially when dealing with inheritance




回答3:


The fact that it is an AJAX call doesn't have anything to do with it, but the fact that the calling code is above the class declaration does.

Swap the code, or even better, move it to a separate file.



来源:https://stackoverflow.com/questions/12675835/class-not-found-in-the-same-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!