php namespace and autoload - php

I have some class
/library/QPF/Loader.php
namespace QPF;
class Loader
{
protected static $loader = null;
public function __construct()
{
spl_autoload_register('QPF\Loader::_autoload');
}
public static function init()
{
if (null === self::$loader) {
self::$loader = new Loader();
}
return self::$loader;
}
public function _autoload($class)
{
//if (class_exists($class)) return true;
$classFile = str_replace('\\', '/', $class) . '.php';
require_once $classFile;
if (!class_exists($class)) throw new Extension('Not found class');
}
}
/library/Version.php
namespace QPF;
class Version
{
public function getVersion()
{
return '0.1';
}
}
/public/index.php
set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/../library');
define('APPLICATION_PATH', dirname(__FILE__) . '/../application');
require_once 'QPF/Loader.php';
QPF\Loader::init();
echo 'start';
use QPF;
$v = new QPF\Version();
var_dump($v);
echo 'ss';
Version class loading, but var_dump show what it's empty class without function getVersion();
startobject(QPF\Version)#2 (0) { } ss

Methods do not show up in var_dump or print_r output, as they are not part of the state of the object. Try calling the method; it should work as expected.

Related

How to create an object from a class inside another class

I have a problem creating an object from another class inside the constructor of my kernel class, it gives a fatal error which says can not find the class, anybody can help please? I do not know what is wrong?
namespace App\Http;
use App\Http\Config;
use App\Controllers;
class kernel{
protected $controller = "HomeController";
protected $action = "index";
protected $params=[];
public function __construct(){
$url = $this->ParseUrl();
$format_url = ucfirst($url[0]) . "Controller";
if (file_exists(Config::CONTROLLERS_PATH . $format_url . ".php")) {
$this->controller = $format_url;
}
// $path = Config::CONTROLLERS_PATH . $this->controller . ".php";
// echo "path: $path";// path is correct
require_once (Config::CONTROLLERS_PATH . $this->controller . ".php");
// $include_file = get_required_files();
// var_dump($include_file);//require_once is working
//here is the problem
$this->controller = new $this->controller;
}
public function ParseUrl(){
if (isset($_GET['url'])) {
return explode("/", rtrim($_GET['url'], "/"));
}
}
}

Error: Calling a class for no reason

The error is:
Class 'Controller\Index' not found
but in all my code at any time I call this class:
Test.php << Script Executor
include_once("index.engine.php");
Index::importController();
use Controller\User;
echo User::getWorld(); // The error happens here.
Index.engine.php << Indexer Includes
if (!defined('HOME')) define("HOME", __DIR__."/");
class Index{
public static function importModel(){
spl_autoload_register(function ($class) {
$nome = str_replace("\\", "/" , $class . '.model.php');
if( file_exists( HOME . $nome ) ){
include_once( HOME . $nome );
}
});
}
public static function importController(){
spl_autoload_register(function ($class) {
$nome = str_replace("\\", "/" , $class . '.controller.php');
if( file_exists( HOME . $nome ) ){
include_once( HOME . $nome );
}
});
}
public static function importPersistent(){
spl_autoload_register(function ($class) {
$nome = str_replace("\\", "/" , $class . '.persistent.php');
if( file_exists( HOME . $nome ) ){
include_once( HOME . $nome );
}
});
}
}
user.controller.php << Only an intermediary
namespace Controller{
include_once (__DIR__ ."/../index.engine.php");
Index::importPersistent();
use Persistent\Test;
class User{
public static function getWorld(){
$result = Test::getEngine();
return $result;
}
}
}
user.persistent.php << Function required
namespace Persistent{
class Test{
public static function getEngine(){
$engine = "Engine is on! \o/";
return $engine;
}
}
}
Thanks for help me.
use Controller\User; # this is used to call a namespace, in your code there is no declaration of the namespace
echo User::getWorld(); //
For this, one would be expected to have a file in this form
sample.php
namespace Controller;
class User {
public static function getWorld() {
...
}
}
user.controller.php
namespace Controller{
include_once (__DIR__ ."/../index.engine.php");
Index::importPersistent();
use Persistent\Test;
class User{
public static function getWorld(){
$result = Test::getEngine();
return $result;
}
}
}
I change to:
namespace Controller{
use Index;
use Persistent\Test;
Index::importPersistent();
class User{
public static function getWorld(){
$result = Test::getEngine();
return $result;
}
}
}
The error was in the include which was called more than once, then altered to call only once in the view.

Class not found PHP Nova Pochta

I have 2 files:
1:
include_once 'Core/autoload.php';
if (!defined('NOVA_POSHTA_PATH_SDK')) {
define('NOVA_POSHTA_PATH_SDK', dirname(__FILE__) . '/');
\NovaPoshta\Core\Autoload::init();
}
autoload:
namespace NovaPoshta\Core\;
class Autoload
{
public static function init()
{
if (function_exists('__autoload')) {
spl_autoload_register('__autoload');
}
return spl_autoload_register(array('\NovaPoshta\Core\Autoload', 'load'));
}
public static function load($className)
{
$className = str_replace('NovaPoshta\\', '', $className);
$className = NOVA_POSHTA_PATH_SDK . $className . '.php';
$className = str_replace('\\', DIRECTORY_SEPARATOR, $className);
if ((file_exists($className) === false) || (is_readable($className) === false)) {
return false;
}
require($className);
return true;
}
}
If executing first code i recive this error:
Class 'NovaPoshta\Core\Autoload' not found
Help me pls. What can be is? Thanks

PHP require files when use namespace

I'm new to PHP namespace. and there is a problem when I use auto-load.
ROOT/Application/Instance.php
<?php
namespace Application;
class Instance {
public static $_database;
public function __construct() {
self::$_database = new \Application\Module\Database();
}
public static function database() {
return self::$_database;
}
public static function ID(){
return md5(uniqid(mt_rand(), TRUE) . mt_rand() . uniqid(mt_rand(), TRUE));
}
public static function autoload($_className) {
$thisClass = str_replace(__NAMESPACE__.'\\', '', __CLASS__);
$baseDir = __DIR__;
if (substr($baseDir, -strlen($thisClass)) === $thisClass) {
$baseDir = substr($baseDir, 0, -strlen($thisClass));
}
$_className = ltrim($_className, '\\');
$fileName = $baseDir;
$namespace = '';
if ($lastNsPos = strripos($_className, '\\')) {
$namespace = substr($_className, 0, $lastNsPos);
$_className = substr($_className, $lastNsPos + 1);
$fileName .= str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $_className) . '.php';
if (file_exists($fileName)) {
require $fileName;
}
}
public static function registerAutoloader() {
spl_autoload_register(__NAMESPACE__ . "\\Instance::autoload");
}
}
ROOT/Application/Module/Database.php
<?php
namespace Application\Module;
include 'FluentPDO/FluentPDO.php';
class Database extends Module {
public static $_instance;
public function __construct() {
if(self::$_instance === NULL) {
self::$_instance = new FluentPDO(new PDO("mysql:host=8273639.mysql.rds.aliyuncs.com;dbname=db", 'name', 'password'));
}
}
}
When I run this:
new \Application\Instance();
I got this error:
Fatal error: Class 'Application\Module\FluentPDO' not found in /mnt/www/airteams_com/public/Application/Module/Database.php on line 13
I'm pretty sure that 'FluentPDO/FluentPDO.php' exists. and the error shows a wrong path of the file. the right path is 'ROOT/Application/Module/FluentPDO/FluentPDO.php'
So how can i use a no namespace class in my situation? thanks.
When you are working with namespaces you must fully qualify each class unless it's a child of the current namespace.
As such the FluentPDO is probably on the root namespace which means you need to access it like such:
self::$_instance = new \FluentPDO(new \PDO("mysql:host=8273639.mysql.rds.aliyuncs.com;dbname=db", 'name', 'password'));

Access Property of class in parent namespace

I have two class, main class is app.php in root directory, and db.php in \system
How To Get property $config in class base, with namespace pattern??
I want to get $config in class base, this is what I want
I define config for hostname,user,pass
then I declare base class wit new \App\base
I can get config in class db
<?php
// \App.php
namespace App;
class base{
private $config;
private $db;
function __construct($config){
$this->config = $config;
$this->db = new \App\system\db;
}
public function getTest() {
return $this->test;
}
}
function load($namespace) {
$splitpath = explode('\\', $namespace);
$path = '';
$name = '';
$firstword = true;
for ($i = 0; $i < count($splitpath); $i++) {
if ($splitpath[$i] && !$firstword) {
if ($i == count($splitpath) - 1) {
$name = $splitpath[$i];
} else {
$path .= DIRECTORY_SEPARATOR . $splitpath[$i];
}
}
if ($splitpath[$i] && $firstword) {
if ($splitpath[$i] != __NAMESPACE__) {
break;
}
$firstword = false;
}
}
if (!$firstword) {
$fullpath = __DIR__ . $path . DIRECTORY_SEPARATOR . $name . '.php';
return include_once ($fullpath);
}
return false;
}
function loadPath($absPath) {
return include_once ($absPath);
}
spl_autoload_register(__NAMESPACE__ . '\load');
?>
<?php
// \System\db.php
namespace App\system;
class db{
private $config;
function __construct(){
$this->config = "How To Get property $config in class base, with namespace pattern??";
}
}
?>
I would suggest you something like this:
class db{
private $test;
function __construct(){
include('../app.php');
$app = new base();
$this->test = $app->getTest();
}
}
Well, just pass the config when you create the db object. Also use the use keyword for better readability.
\App
namespace App;
use \App\system\db;
class base {
private $config;
private $db;
function __construct($config){
$this->config = $config;
$this->db = new db($config);
}
public function getTest() {
return $this->test;
}
}
\System\db.php
namespace App\system;
class db {
private $config;
function __construct($config){
$this->config = $config;
}
}

Categories