Otak
Otak

Reputation: 11

PHP default spl autoload function do not load parent of class in namespace

I cannot autoload parent of class in namespace. Without inheriting child class is loaded; but child is not able to autoload parent class.

File structure:

/index.php
/lib/router.php
/lib/ns1/parent1.php
/lib/ns1/child1.php

index.php:

spl_autoload_extensions(".php");
spl_autoload_register();
require '/lib/router.php';

/lib/router.php

$child1 = new ns1\child1();

/lib/ns1/child1.php

namespace ns1;
class child1 extends parent1 {}

/lib/ns1/parent1.php

namespace ns1;
class parent1 { function __construct() {} }

When I remove "extends" part from child1 everything is ok. With "extends" part I have error:

Fatal error: spl_autoload(): Class parent1\child1 could not be loaded in /lib/ns1/child1.php

Is there some way how to do that with built in default spl autoload function? Many thanks for any help.

Upvotes: 0

Views: 403

Answers (1)

Otak
Otak

Reputation: 11

I found the solution which works for me in this answer https://stackoverflow.com/a/7987085/5208203

Just add set_include_path() to file index.php:

set_include_path(get_include_path().PATH_SEPARATOR."/lib");
spl_autoload_extensions(".php");
spl_autoload_register();
require '/lib/router.php';

But I'm not sure about performance, may be it is just workaround for another failure I have in my class definitions...

Upvotes: 0

Related Questions