0

B.php:

   class B
   {
   function show() { echo 'works'; }
   }

A.php

class A
{

 public static function defineB()
 {
  include "b.php";
 }

}


A::defineB();
$b = new B;
var_dump($b);

object(B)#1 (0) { } ,

if without A::defineB(); - Fatal error: Class 'B' not found , if define class without including another file - Fatal error: Class declarations may not be nested ,

is it bug ?

John Faker
  • 38
  • 2
  • It is a bug, but not in PHP. You can't nest class declarations as the error message says. – JJJ Apr 03 '12 at 13:03
  • 1
    possible duplicate of [is it allowed to create a php class inside another class](http://stackoverflow.com/questions/1583140/is-it-allowed-to-create-a-php-class-inside-another-class) – JJJ Apr 03 '12 at 13:04
  • What version of PHP do you use? Given [this question](http://stackoverflow.com/questions/2608432/php-nested-classes-work-sort-of) this should work, since `include()` includes classes in the global namespace. – CodeCaster Apr 03 '12 at 13:05
  • "Given this question this should work, since include() includes classes in the global namespace" if its global , why its isnt defined untill i use A::defineB(); ? – John Faker Apr 03 '12 at 13:10
  • @JohnFaker Just in case you never figured it out, `include()` is not going to put the "included" stuff INSIDE of the function. It simply parses the information. Class declarations and function declarations are not going to be inside of `defineB`, but are instead automatically added to the global scope. – Anther Apr 23 '13 at 17:28

2 Answers2

3

It is not a bug, it is default and correct behaviour.

You should include files before using them. If this gives you too much pain, you could use http://www.php.net/manual/en/language.oop5.autoload.php or http://www.php.net/manual/en/function.spl-autoload-register.php in the beginning of your code.

Nameless
  • 2,306
  • 4
  • 23
  • 28
  • if its not a bug ,why i dont have a error - Fatal error: Class declarations may not be nested ? why code works ? – John Faker Apr 03 '12 at 13:08
0

In PHP you can not nesting classes (as in Java) - so you got "Class declarations may not be nested". The key word is namespace. Including class B from method of class A does not affect the name of class A that is still... "A" and not "B\A", "B.A" or sth. :)

Radek M
  • 379
  • 2
  • 8