0

I have three different files for each part of code. (i use class autoloader). First file (/classes/Test/Foo.php):

<?php
namespace Test;

class Foo
{
  public $id;

  function __construct(int $id)
  {
    $this->id = $id;
  }

  public function get() : string
  {
    return "FOO:" . $this->id;
  }
}

Second file (/classes/Test/Bar.php):

<?php
namespace Test;

class Bar extends Foo
{
  public function get() : string
  {
    return "BAR:" . $this->id;
  } 
}

Third file (/index.php):

<?php
namespace Test;
include "autoloader.php";
$bar = new Bar(1);
echo $bar->get();

When i execute third file i didn't get any output at all, not even error ...but if i put all code in one file it works.

<?php
namespace Test;

class Foo
{
  public $id;

  function __construct(int $id)
  {
    $this->id = $id;
  }

  public function get() : string
  {
    return "FOO:" . $this->id;
  }
}

class Bar extends Foo
{
  public function get() : string
  {
    return "BAR:" . $this->id;
  } 
}

$bar = new Bar(1);
echo $bar->get();

output: BAR:1

What could be the problem?

Autoloader code:

<?php
spl_autoload_register(function($class) {
  require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/" . str_replace("\\", "/", $class) . ".php";
});

2 Answers2

0

The file path required in your autoloader will reflect the classname including the namespace - this needs to exactly match the directory structure on disk.

Within the callback to spl_autoload_register, $class will first be passed in as Test\Bar. This results in it attempting to include the file classes/Test/Bar.php, which doesn't exist. This will be throwing a fatal error - it sounds like your error reporting settings aren't configured to display this.

For the files you've posted, your directory structure needs to look like this:

.
├── classes
│   └── Test
│       ├── Bar.php
│       └── Foo.php
├── autoloader.php
└── index.php
iainn
  • 15,089
  • 9
  • 27
  • 37
0

Solved the problem! This code was example, but in actual code, overridden method had different return type (int instead of string).