I’m trying to implement spl_autoload_register() in a project I am working on. Previously when using classes i just included and initiated them separately. A class would look like:
require_once('connect.php');
class Get_NEWS {
protected $pdo;
function __construct($pdo) {
$this->pdo = $pdo;
}
function get_id(){
$qry = "SELECT MIN(news_id) AS news_id
FROM news
WHERE isNew = 1";
$stmt = $this->pdo->query($qry);
$row = $stmt->fetch();
$this->new= $row['news_id'];
echo $this->news;
}
Then on any page I would include and initiate the class
include_once "classes/get_news.php";
$news = new Get_News($pdo);
But when I try to use spl_autoload_register() the following way:
function auto_loader($file){
require 'classes/' . $file . '.php';
}
spl_autoload_register('auto_loader');
$news = new Get_News($pdo);
I get the error Undefined variable: pdo. What is wrong with this approach? Thank you all in advance
There is nothing wrong with your approach. The problem is as stated in the error message you’re receiving: you aren’t defining the $pdo variable in your script prior to using it as a constructor argument for your Get_News class.
I would, however, advise you to shift the autoloader into a file unto itself so that you can easily include it into other pages. This will mean that you need to shift the last assignment statement out of the above snippet.
autoloader.php
function auto_loader($file){
require 'classes/' . $file . '.php';
}
spl_autoload_register('auto_loader');
script.php
require 'autoloader.php';
$pdo = new PDO('dsn here', 'username', 'pws');
$news = new Get_News($pdo);
Be mindfull of classnames and file names! On windows this will work since it is case insensitive. To let it work you should rename the class file to Get_NEWS.php.
You’re correct, his file should be called Get_News.php and not Get_NEWS.php. @rvincenten was probably trying to mimic the actual class name, rather than the invoked class name (and since PHP’s class and method names are case-insensitive, it’s the invoked class name that will needs to be mimicked).
Ah. I didn’t read the original question close enough. The OPer really should invoke the class with Get_NEWS and have the file be named Get_NEWS just for consistency as well as avoiding case sensitivity issues. .