简体   繁体   中英

PHP - Extend parent class from child class which is in another directory

I try to create a parent class for all my "Model" classes.

I have a class in app/code/core/User/Model/User.php named User_Model_User it should inherit from a parent class in app/code/core/Core/Model.php

在此处输入图片说明

Attempt:

Parent:

class Model
{
    public function testParent()
    {
        echo "123";
    }
}

Child:

class User_Model_User extends Core\Model
{
    private $con;
    private $user_id;

    public function __construct($con)
    {
        $this->con = $con;
    }

    public function loadByEmail($email)
    {
        $this->user_id = $this->getUserId($email);
        return $this;
    }
...

Error:

Fatal error: Class 'Core\\Model' not found in /var/www/property-rights/app/code/core/User/Model/User.php

How does it work?

Not sure if this is the best way, but I solved it like this:

Main: app/Main.php

Put <project_root>/app/code/core in include path, so that I don't have to use the full path when calling include , require etc.

if (!defined('DS')) define('DS', DIRECTORY_SEPARATOR);
if (!defined('PS')) define('PS', PATH_SEPARATOR);
if (!defined('BP')) define('BP', dirname(dirname(__FILE__)));

Main::register('original_include_path', get_include_path());

$paths = array();
$paths[] = BP . DS . 'app' . DS . 'code' . DS . 'core';
$paths[] = BP . DS . 'app' . DS . 'code' . DS . 'local';
$paths[] = BP . DS . 'lib';
$paths[] = BP . DS . 'inc';

$appPath = implode(PS, $paths);
set_include_path($appPath . PS . Main::registry('original_include_path'));

Parent:

namespace Core;

class Model
{

Child:

require_once("Core/Model.php");

class User_Model_User extends Core\Model
{

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM