55

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
                )
        );
    } 
}

?>
siannone
  • 6,386
  • 13
  • 55
  • 87

19 Answers19

53

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.

jarederaj
  • 1,240
  • 13
  • 18
38
if ( ! class_exists('User')) 
    die('There is no hope!');
Dejan Marjanović
  • 19,004
  • 7
  • 50
  • 66
32

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

random
  • 9,571
  • 10
  • 67
  • 79
Raiden616
  • 1,454
  • 3
  • 17
  • 38
  • 2
    Damn why you bring me memories of my old code, it was awful :( – siannone Sep 23 '16 at 11:04
  • Same here. And the class was being used elsewhere, so I knew it was supposed to be working all right. But that other place was under the same namespace unlike this one. – Jānis Elmeris Oct 25 '19 at 15:07
  • Same problem here. And **how** to fix that? I tried "use namespacename/classname" without luck, but it cannot be included into a method. See https://stackoverflow.com/a/33355711/1066234 – Avatar Dec 04 '19 at 09:15
  • In my case, I removed the "namespace lib;" from the included file, and then included each necessary PHP file into the function I was using with `require_once`. – Avatar Dec 04 '19 at 09:27
8

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.*",
olga
  • 839
  • 1
  • 12
  • 34
7

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

var_dump(file_exists($ENGINE."/classUser.php"));
Minras
  • 3,630
  • 4
  • 16
  • 17
  • 28
    Useless... require_once() will kill the script with a fatal error if the file can't be found or read. – Marc B Dec 13 '11 at 14:24
  • I receive `bool(false)`, but when i execute `echo $ENGINE."/classUser.php";` i receive `http://localhost/webname/resources/engine/classUser.php` which is correct – siannone Dec 13 '11 at 14:24
  • Just as a follow up, try `var_dump`ing `$ENGINE."/classUser.php"` as well just to see what it is if `file_exists` returns false. Also permissions could be your friend/enemy too – James Butler Dec 13 '11 at 14:24
  • 3
    'http: //localhost' is a bit worrying... why aren't you using the local filesystem? – James Butler Dec 13 '11 at 14:25
  • If i use filesystem path i get php errors. I've asked around whether to use full path or URL path. They said the second one was better. – siannone Dec 13 '11 at 14:28
  • In `require` you should use a path to a file in a filesystem, not its URL. – Minras Dec 13 '11 at 14:28
  • 2
    You can include URLs, but in your case you are trying to include not a content of a file but its output which is empty of course. – Minras Dec 13 '11 at 14:30
  • 1
    For general sanity (and reduce the number of things which can go wrong), (and to make the world a better place), please don't http unless you have to for file includes (and if you do, change your design!) – James Butler Dec 13 '11 at 14:36
  • Ok, i solved the problem by using `require_once("../classUser.php");` but in don't think it's a good way. What's a good way of doing that? – siannone Dec 13 '11 at 14:39
  • 1
    The $ENGINE variable doesn't make sense to me - It should point to your main PHP engine, not to a HTTP path. – Mick Hansen Dec 13 '11 at 14:41
3

The problem went away when I did

sudo service apache2 restart
Russell England
  • 8,493
  • 1
  • 25
  • 40
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!

Lorenzo Magon
  • 535
  • 5
  • 16
1

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

Andrew
  • 3,415
  • 4
  • 29
  • 37
1

In fact, it's a very old thread but useful...

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 } ?>
ekad
  • 14,056
  • 26
  • 43
  • 45
1
  1. Check File Permissions
  2. Check File size.

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

Cedric Ipkiss
  • 4,532
  • 2
  • 39
  • 59
1

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 ...

CodeToLife
  • 2,981
  • 2
  • 35
  • 25
1

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.

Jeff Solomon
  • 417
  • 6
  • 20
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
    }
} 
Minras
  • 3,630
  • 4
  • 16
  • 17
0

After nearly two hours of debugging I have concluded that the best solution to this is to give the file name a different name to the class that it contains. For Example:

Before example.php contains:

<?php
 class example {

 }

Solution: rename the file to example.class.php (or something like that), or rename the class to example_class (or something like that)

Hope this helps.

  • And why would that be the best solution? How did you realize that? What you say is totally a bad idea. And by the way, try using Composer with your "best solution" and let me know how it goes ;) P.S. when you come back and realize that what you just said is actually a bad idea give a read to this: http://www.php-fig.org/psr/psr-4/ – siannone Apr 17 '16 at 11:22
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.
Andrew
  • 16,273
  • 10
  • 93
  • 104
0

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

$user = new \resources\engine\ajax\User();
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()

skmak
  • 357
  • 3
  • 12
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();
Wael Salah
  • 51
  • 1
  • 7
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');
Spinstaz
  • 119
  • 4
  • 8