Webeng Webeng - 6 months ago 80
PHP Question

Fatal Error: Class 'Pheanstalk\Pheanstalk` not found

I am using a library that I downloaded with composer called Pheanstalk. I am running the following script:

<?php

//... some unrelated code

require_once('vendor/autoload.php'); //loading the autoload file from composer
use Pheanstalk\Pheanstalk; //using the namespace
$pheanstalk = new Pheanstalk('127.0.0.1'); //initiating an object

//... some unrelated code

?>


The following error appears:

Fatal Error: Class 'Pheanstalk\Pheanstalk' not found in /opt/lampp/htdocs/project_zero/index.php on line 16


with line 16 being:
$pheanstalk = new Pheanstalk('127.0.0.1');


Question: Why might I be getting this error? The script above was basically copy-paisted from the Usage Example given on the Pheanstalk github page: https://github.com/pda/pheanstalk.

The contents of my
composer.json
file are:

{
"require": {
"pda/pheanstalk": "2.1.1"
}
}





EDITED:

New errors when using:

use \Pheanstalk_Pheanstalk


Errors:

Warning: The use statement with non-compound name 'Pheanstalk_Pheanstalk' has no effect in /opt/lampp/htdocs/project_zero/index.php on line 14

Fatal error: Class 'Pheanstalk' not found in /opt/lampp/htdocs/project_zero/index.php on line 17

Answer

According to your composer.json, you are using version 2.1.1: https://github.com/pda/pheanstalk/blob/2.1/classes/Pheanstalk/Pheanstalk.php

The class name is Pheanstalk_Pheanstalk not Pheanstalk\Pheanstalk: it was not PSR-4 compliant at this moment.

So you should just use:

<?php
use \Pheanstalk_Pheanstalk;

when you're in a namespaced file. If you don't use namespace in a file, you don't need to "import" the class.

Backslash is important if you use namespaces, because the class, in version 2.x was not namespaced.

UPDATE

So your code should be like this:

<?php

//... some unrelated code

require_once('vendor/autoload.php');        //loading the autoload file from composer
$pheanstalk = new Pheanstalk_Pheanstalk('127.0.0.1');  //initiating an object

//... some unrelated code

?>

That's all.