【问题标题】:PHP - Extend parent class from child class which is in another directoryPHP - 从另一个目录中的子类扩展父类
【发布时间】:2020-01-11 03:14:09
【问题描述】:

我尝试为我的所有“模型”类创建一个父类。

我在app/code/core/User/Model/User.php 中有一个名为User_Model_User 的类,它应该继承自app/code/core/Core/Model.php 中的父类

尝试:

家长:

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

孩子:

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;
    }
...

错误:

致命错误:在中找不到类“Core\Model” /var/www/property-rights/app/code/core/User/Model/User.php

它是如何工作的?

【问题讨论】:

  • 你的班级有命名空间吗?您需要提供更多示例代码,以便我们排除任何问题。
  • 但是父类有命名空间吗?您不能纯粹基于文件夹结构扩展某些内容。你需要这个类有一个命名空间,然后你可以从中扩展。
  • 不,它没有命名空间。
  • 您的问题肯定与您在类上没有命名空间有关。当你像Core\Model 一样扩展时,你就是在扩展命名空间,但由于它没有,你不能从它扩展。添加命名空间,然后我确定它可以工作。
  • @SeverinDK,我昨天已经解决了。请看我的回答,我不确定这是否是最好的方法。

标签: php class inheritance


【解决方案1】:

不确定这是否是最好的方法,但我是这样解决的:

主要: app/Main.php

<project_root>/app/code/core放入包含路径,这样我在调用includerequire等时就不必使用完整路径了。

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'));

家长:

namespace Core;

class Model
{

孩子:

require_once("Core/Model.php");

class User_Model_User extends Core\Model
{

【讨论】:

    猜你喜欢
    • 2014-08-18
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2013-07-18
    • 2011-10-31
    相关资源
    最近更新 更多