从另一个具有名称空间的类(PHP)调用方法

时间:2019-01-07 21:48:42

标签: php class oop namespaces

我在上课时遇到问题。我正在将https://www.php-fig.org/psr/psr-4/用于自动加载类。

------------------------------------ /home/classes/a/casea.php < / p>

build.gradle

------------------------------------ /home/classes/b/caseb.php < / p>

namespace Classes\A\CaseA;

class ClassA {

  public function MethodA()

  {

    $resultA = 'Method A works!';
    return $resultA;

  }

}

------------------------------------自动加载

namespace Classes\B\CaseB;

class ClassB {

  public function MethodB()

  {

    // Classes\A\CaseA\ClassA  MethodA() don't work here.
    // I tried this, but didn't work.
    $obj = new Classes\A\CaseA\ClassA;
    $result = $obj->MehodA();

    return $result;

  }

}

$classb = new Classes\B\CaseB\ClassB;
$show = $classb->MethodB();
echo $show;

错误是以下文本。

## PHP-FIG Autoload
spl_autoload_register(function ($class) {

    // project-specific namespace prefix
    $prefix = 'Classes\\';

    // base directory for the namespace prefix
    $base_dir = PATH . '/classes/';

    // does the class use the namespace prefix?
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        // no, move to the next registered autoloader
        return;
    }

    // get the relative class name
    $relative_class = substr($class, $len);

    // replace the namespace prefix with the base directory, replace namespace
    // separators with directory separators in the relative class name, append
    // with .php
    $file = $base_dir . strtolower(str_replace('\\', '/', $relative_class)) . '.php';

    // if the file exists, require it
    if (file_exists($file)) {
        require $file;
    }

});

1 个答案:

答案 0 :(得分:-1)

我解决了这个问题,如果有人需要,可以使用以下代码。

在caseb.php

namespace Classes\B\CaseB;

use Classes\A\CaseA\ClassA;

class ClassB extends ClassA {

  public function MethodB()

  {

    $result = parent::MehodA();

    return $result;

  }

}