Class Not found when autoloading with namespace (no Composer) - php

I have been checking for answers but with no success. I'm not using composer autoload function.
I'm trying to test some classes, Collections and traits in a index.php.
The problem is when i'm including a namespace, I'have created the _autoload function (No composer) to load a class when needed. If I execute php index.php i'm getting the class not found error.
I have tried the use command, but with no success as well.
It solves when I include each class one by one like this:
include_once __DIR__ . '/Collection.php';
include_once __DIR__ . '/User.php';
include_once __DIR__ . '/Tweet.php';
include_once __DIR__ . '/UserCollection.php';
include_once __DIR__ . '/TweetCollection.php';
Thats my index.php:
<?php
namespace phpexercises\entregableT3;
error_reporting(E_ALL);
ini_set( "display_errors", "on" );
/*
include_once __DIR__ . '/Collection.php';
include_once __DIR__ . '/User.php';
include_once __DIR__ . '/Tweet.php';
include_once __DIR__ . '/UserCollection.php';
include_once __DIR__ . '/TweetCollection.php';
*/
use phpexercises\entregableT3\User;
function __autoload($classname){
require __DIR__ . "/" . $classname . ".php";
}
//UserCollection pruebas
$alex = new User();
$jumbo = new User();
$users = new UserCollection();
$alex->phone = "682383";
$alex->email = "alex#example.com";
$alex->city = "BCN";
$alex->gender = "Male";
$jumbo->phone = "54534535";
$jumbo->email = "jumbo#example.com";
$jumbo->city = "elche";
$jumbo->gender = "Male";
$users->add($alex);
$users->add($jumbo);
print_r($users->findByEmail("alex#example.com"));
print_r($users->findByGender("Female"));
//Tweet Collection pruebas
$tweet = new Tweet();
$tweet->email = "alex#example.com";
$tweet->text = "This is a tweet";
$tweet->date = date("D:M:Y");
$tweet1 = new Tweet();
$tweet1->email = "alex#example.com";
$tweet1->text = "This is a tweet";
$tweet1->date = date("D:M:Y");
When I uncomment the requires, everything works fine, but it is not the way to load all classes...Any idea for this behaviour? How should I load the classes at same time?
Thanks

Related

Unable to trace require_once error in PHP

i have a file structure like this in my PHP 7.1
Model/Abstract.php
Model/NTLStm.php
Model/SoapCl.php
Controller.php
i Called Model/Abstract.php in Controller like this:
use Model/Abstract as modelAbstract;
$abstract = new modelAbstract();
i tried to include the Model/NTLStm.php & Model/SoapCl.php in Model/Abstract.php like this:
defined('DS') OR define('DS', DIRECTORY_SEPARATOR);
require_once dirname(__FILE__) . DS . 'SoapCl.php';
require_once dirname(__FILE__) . DS . 'NTLStm.php';
echo 'success';
but it seems it always terminate the process in require_once , i already tried to put try catch like this:
try{
defined('DS') OR define('DS', DIRECTORY_SEPARATOR);
require_once dirname(__FILE__) . DS . 'SoapCl.php';
require_once dirname(__FILE__) . DS . 'NTLStm.php';
} catch(\Exception $e){
echo $e->getMessage();
}
but it won't print anything
Try using parentheses with require_once... like this:
require_once (dirname(__FILE__) . DS . 'SoapCl.php');
require_once (dirname(__FILE__) . DS . 'NTLStm.php');

instagram php scraping (gives error)

I am pretty new to PHP so this may be a dumb question but yeah. I'm trying to get information about a user on instagram with this library: https://github.com/postaddictme/instagram-php-scraper
I've added the library and also the Unirest library so that it should work?
I also have this code in my index.php file:
<?php
require_once dirname(__FILE__) . '/Unirest/Exception.php';
require_once dirname(__FILE__) . '/Unirest/Method.php';
require_once dirname(__FILE__) . '/Unirest/Response.php';
require_once dirname(__FILE__) . '/Unirest/Request.php';
require_once dirname(__FILE__) . '/Unirest/Request/Body.php';
require_once dirname(__FILE__) . '/InstagramScraper/Instagram.php';
require_once dirname(__FILE__) . '/InstagramScraper/Endpoints.php';
require_once dirname(__FILE__) . '/InstagramScraper/Model/Account.php';
require_once dirname(__FILE__) . '/InstagramScraper/Model/Comment.php';
require_once dirname(__FILE__) . '/InstagramScraper/Model/Location.php';
require_once dirname(__FILE__) . '/InstagramScraper/Model/Media.php';
require_once dirname(__FILE__) . '/InstagramScraper/Model/Tag.php';
require_once dirname(__FILE__) . '/InstagramScraper/Exception/InstagramException.php';
require_once dirname(__FILE__) . '/InstagramScraper/Exception/InstagramAuthException.php';
require_once dirname(__FILE__) . '/InstagramScraper/Exception/InstagramNotFoundException.php';
use InstagramScraper\Instagram;
$account = Instagram::getAccountById(272308256);
echo $account->username;
?>
But this code does not want to run :/. I keep getting this error:
Fatal error: Using $this when not in object context in
C:\xampp\htdocs\Instagramposts\InstagramScraper\Instagram.php on line 313
I mean if it's a finished library it should immediately work? Anybody's got a solution?
You need to create an instance of the class (object) first before using the method. The method makes use of the "this" operator which needs an object.
Your code should look like this:
use InstagramScraper\Instagram;
$insta = new Instagram;
$account = $insta->getAccountById(272308256);
echo $account->username;

After wordpress upgrade I'm getting wp_user not found in pluggable.php

I am calling a php script from an app that checks the credentials of a wp user. This worked fine until I upgraded wordpress from 4.3 to 4.4 (and 4.5). It's really time I got this sorted but I can't think why wp-user is no longer available as it is in the include list.
error: wp_user not found in pluggable.php
Please see the code below..
define( 'SHORTINIT', TRUE );
require_once $abspath . '/wp-load.php';
require_once $abspath . '/wp-includes/user.php';
require_once $abspath . '/wp-includes/pluggable.php';
require_once $abspath . '/wp-includes/formatting.php';
require_once $abspath . '/wp-includes/capabilities.php';
require_once $abspath . '/wp-includes/kses.php';
require_once $abspath . '/wp-includes/meta.php';
require_once $abspath . '/wp-includes/l10n.php';
require_once $abspath . '/wp-includes/class-wp-error.php';
require_once $abspath . '/wp-includes/general-template.php';
require_once $abspath . '/wp-includes/link-template.php';
$the_authenticate = wp_authenticate_username_password('null',$user_name,$user_password);
if( is_wp_error( $the_authenticate ) ) {
echo '{"error":"The username was not recognised"}';
}
else
{
$the_user_authenticate_id = $the_authenticate->ID;
$the_user = get_user_by('login', $user_name);
$the_user_id = $the_user->ID;
if ( !$the_user )
{
//echo "{'error':'The username was not recognised'}";
}
I have found the solution is that I now need to include the following..
require_once $abspath . '/wp-includes/class-wp-roles.php';
require_once $abspath . '/wp-includes/class-wp-user.php';
require_once $abspath . '/wp-includes/class-wp-role.php';
Please can anyone explain why these extra includes are suddenly necessary in wordpress 4.4 and whether my solution makes sense?
Download the updated wordpress version from wordpress.org and replace your current wp-admin and wp-includes folders with updated wordpress folders.
Hope it will work.

spl_autoload_register() in different directories

I have a file that auto loads each of my classes.
This is what it contains:
spl_autoload_register(function($class){
require_once 'classes/' . $class . '.php';
});
require_once 'functions/sanitize.php';
require_once 'functions/hash.php';
But when I require_once this file from another php file that is inside my ajax folder, it will try looking for the classes, the function will look from my classes with the path: main_folder/ajax/classes instead of just main_folder/classes.
Does anyone know how to fix this?
FIX:
spl_autoload_register(function($class){
if (file_exists('classes/' . $class . '.php')) {
require_once 'classes/' . $class . '.php';
}
elseif (file_exists('../classes/' . $class . '.php')) {
require_once '../classes/' . $class . '.php';
}
elseif (file_exists('../../classes/' . $class . '.php')) {
require_once '../../classes/' . $class . '.php';
}
You should simple use this function just once - in the main file (usually index.php) and not in another files.
However if it's not possible (but I don't see any reason when could it be not possible) you can change it for example that way:
spl_autoload_register(function($class){
if (file_exists('classes/' . $class . '.php')) {
require_once 'classes/' . $class . '.php';
}
elseif (file_exists( $class . '.php')) {
require_once $class . '.php';
}
});
Here is a proper way, It should universally work.
EDIT: Make sure to specify levels on dirname in order to find the correct path.
spl_autoload_register(function ($classname) {
$file_realpath = dirname(realpath(__FILE__), levels: 1 /* Change that? */) . DIRECTORY_SEPARATOR . dirname($classname);
$classpath = sprintf('%s' . DIRECTORY_SEPARATOR . '%s.php', $file_realpath, basename($classname, '.{php,PHP}'));
if (file_exists($classpath)) {
echo "Loading <b>$classpath</b>...<br>";
require($classpath);
}
});
You need to know the absolute path to the classes directory, then just use a full qualified path to get there.
Make sure your document root is correctly configured with your http server. Furthermore this is usually solved by routing all requests to index.php and deriving the base path (document root) from there. Here is your code modified:
spl_autoload_register(function($class) {
$resolved = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . $class . '.php';
if(file_exists($resolved)) {
require_once $resolved;
} else {
// make it known to your that a class failed to load somehow
return;
}
})
Here is another implementation that I use for simple projects

PHP autoload oddity

function __autoload($class_name) {
echo("Attempting autoload ");
if (substr($class_name, -6) == "Mapper") {
$file = 'mappers/'.$class_name.'.php';
echo "Will autoload $file ";
include_once($file);
}
}
__autoload("UserMapper");
$user = new UserMapper($adapter);
die("done");
Result:
Attempting autoload Will autoload mappers/UserMapper.php done
function __autoload($class_name) {
echo("Attempting autoload ");
if (substr($class_name, -6) == "Mapper") {
$file = 'mappers/'.$class_name.'.php';
echo "Will autoload $file ";
include_once($file);
}
}
//__autoload("UserMapper");
$user = new UserMapper($adapter);
die("done");
(I just commented out the manual call to __autoload()...)
Result:
Fatal error: Class 'UserMapper' not found in C:\Program Files\EasyPHP-5.3.5.0\www\proj\29letters\login.php on line 13
Any ideas?
And yes, I'm running PHP 5.3.5
Not sure why your example isn't working, as it should be as per the manual.
Have you tried using spl_autoload_register to register the autoloader function?
Have you set a proper include_path? You're using a relative path to include the class's file. Try an absolute path instead.
$dir = __DIR__ . '/../path/to/mappers';
$file = $dir . '/' . $class_name . '.php';
require $file;
or
// do this outside of __autoload
set_include_path(get_include_path() . PATH_SEPARATOR . __DIR__ . '/../path/to/mappers';
// inside __autoload
$file = $class_name . '.php';
require $file;

Categories