问题
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