70

I'm including a PHP class with

require_once($ENGINE."/classUser.php");

but when the code is executed i receive this error:

Fatal error: Class 'User' not found in C:\xampp\htdocs\WebName\resources\engine\ajax\signup.php on line 12

I still can't figure out what's the problem. I'm 99% sure it's correct.

The "$ENGINE" is correct, and the class is correct too (Netbeans suggests me class methods and variables).

signup.php:

<?php

/* Created on: 13/12/2011
 * Author: 
 * 
 * Description: User signup procedure.
 */

require_once("../settings.php");
require_once($ENGINE."/classUser.php");

$user = new User();
$user->createUser($_POST["username"], $_POST["email"], $_POST["password"]);


?>

classUser.php:

<?php

/* Created on: 13/12/2011
 * Author: 
 * 
 * Description: This class manages users.
 */

require_once("settings.php");
require_once($LIBRARY."/cassandraphp/cassandra.php");

class User {

    public function createUser($username, $email, $password){
        $cassandra = Cassandra::createInstance($CASSANDRASERVER);
        $cassandra->set(
                "user.".$username,
                array(
                    'ID' => uniqid(),
                    'Username' => $username,
                    'Email' => $email,
                    'Password' => $password
                )
        );
    } 
}

?>
0

18 Answers 18

65

Check to make sure your environment isn't being picky about your opening tags. My configuration requires:

<?php

If I try to use:

<?

Then I get the same error as you.

Short tags can be enabled through the INI setting short_open_tag.

Sign up to request clarification or add additional context in comments.

2 Comments

If you dont have access to php.ini, you can add this to .htaccess: php_value short_open_tag 1
Man you saved my week ! ChatGPT gave me code starting by '<?' and I didn't figured out it could be the problem. Thank you !
39

I had this problem and the solution was namespaces. The included file was included in its own namespace. Obvious thing, easy to overlook.

1 Comment

It would be better to explain exactly what the issue with namespaces was in your case.
36
if ( ! class_exists('User')) 
    die('There is no hope!');

Comments

14

It may also be, that you by mistake commented out such a line like require_once __DIR__.'/../vendor/autoload.php'; --- your namespaces are not loaded.

Or you forget to add a classmap to the composer, thus classes are not autoloaded and are not available. For example,

"autoload": {
    "psr-4": {
        "": "src/"
    },
    "classmap": [
        "dir/YourClass.php",
    ]
},
"require": {
    "php": ">=5.3.9",
    "symfony/symfony": "2.8.*",

Comments

6

First of all check if $ENGINE."/classUser.php" is a valid name of existing file. Try this:

var_dump(file_exists($ENGINE."/classUser.php"));

1 Comment

Useless... require_once() will kill the script with a fatal error if the file can't be found or read.
4

My fail might be useful to someone, so I thought I would post as I finally figured out what the issue was. I was autoloading classes like this:

define("PROJECT_PATH", __DIR__);

// Autoload class definitions
function my_autoload($class) {
    if(preg_match('/\A\w+\Z/', $class)) {
        include(PROJECT_PATH . '/classes/' . $class . '.class.php');
    }
}
spl_autoload_register('my_autoload');

In my /classes folder I had 4 classes:

dbobject.class.php
meeting.class.php
session.class.php
user.class.php

When I later created a new class called:

cscmeeting.class.php

I started getting the can't load DbObject class. I simply could not figure out what was wrong. As soon as I deleted cscmeeting.class.php from the directory, it worked again.

I finally realized that it was looping through the directory alphabetically and prior to cscmeeting.class.php the first class that got loaded was cscmeeting.class.php since it started with D. But when I add the new class, which starts with C it would load that first and it extended the DbObject class. So it chocked every time.

I ended up naming my DbObject class to _dbobject.class.php and it always loads that first.

I realize my naming conventions are probably not great and that's why I was having issues. But I'm new to OOP so doing my best.

Comments

2

The problem went away when I did

sudo service apache2 restart

Comments

2

you should declare namespace in the ClassUser.php, something like this:

<?php
namespace app; // where 'app' is a folder declared as a root for the project
class ClassUser{
public function test(){
//log something here
}
}
?>

Then you can add the class in your other php files like this:

<?php
use app\ClassUser;
$classUserLcl = new ClassUser();
$classUserLcl->test();
?>

and you are done. Otherwize it will abuse:

You Oh! its a Fatal error : Uncaught Error: Class 'app\ClassUser' not found in ...

Comments

1

As a more systematic and structured solution you could define folders where your classes are stored and create an autoloader (__autoload()) which will search the class files in defined places:

require_once("../settings.php");
define('DIR_CLASSES', '/path/to/the/classes/folder/'); // this can be inside your settings.php

$user = new User();
$user->createUser($_POST["username"], $_POST["email"], $_POST["password"]);

function __autoload($classname) { 
    if(file_exists(DIR_CLASSES . 'class' . $classname . '.php')) {
        include_once(DIR_CLASSES . 'class' . $classname . '.php'); // looking for the class in the project's classes folder
    } else {
        include_once($classname . '.php'); // looking for the class in include_path
    }
} 

Comments

1

It 'happened to me! The problem is that somehow you include a file with the same file name of the class thus invalidating the same class!

Check the path of inclusion and these checks files with the same name!

Comments

1

Check your file permissions for the correct linux user for classUser.php

Comments

1
  1. Check File Permissions
  2. Check File size.

Sometimes an inaccessible or corrupted file would be the problem, as was in my case

Comments

1

When namespace declaration is part of your php class file "this kind of weird errors tends to appear".

Solution: Use namespace with {, your code shows like this:

<?php

namespace path_to\lib {

require_once "folder/php_class_file_where_namespace_declaration_is_part_of_it.php";

**YOUR CODE HERE**

<?php } ?>

Comments

0

Double check your autoloader's requirements & namespaces.

  • For example, does your autoloader require your namespace to match the folder structure of where the file is located? If so, make sure they match.
  • Another example, does your autoloader require your filenames to follow a certain pattern/is it case sensitive? If so, make sure the filename follows the correct pattern.
  • And of course if the class is in a namespace make sure to include it properly with a fully qualified class name (/Path/ClassName) or with a use statement at the top of your file.

Comments

0

Maybe it is how you use new User(). Set path something like

$user = new \resources\engine\ajax\User();

Comments

0

If you've included the file correctly and file exists and still getting error:

Then make sure:
Your included file contains the class and is not defined within any namespace.
If the class is in a namespace then:
instead of new YourClass() you've to do new YourNamespace\YourClass()

Comments

0

Yes this happen in cases when use a trait or extend a class, you should be aware to instantiate the class after the class declaration for example:

This example will trigger class not found error:

$class = new A();

class A {
   use SomeTrait;
}

To make it to work move the initialization step in the bottom like so:

class A {
   use SomeTrait;
}

$class = new A();

Comments

0

I found I had to use the use keyword, as well as the include statement. Tested it with either missing, and it doesn't work.

namespace foo;
use src\config\object;
include('config/object.php');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.