0

I'm just learning the php and came out a question in my mind, Can I define the class within the function like this:

public class test{
  public function newtest(){
    // defining a class here like this:
    public class funclass{
     .....
    }
  }
}
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231

2 Answers2

3

Yes, you can

function a(){
    class A {
        }
    }

var_dump(class_exists('A')); //bool(false)
a();
var_dump(class_exists('A')); //bool(true)

But, remeber that classes are globals. You cannot bound class to function scope only.

sectus
  • 15,605
  • 5
  • 55
  • 97
  • You cannot do so. Put that function `a()` in a class just like they did and then try again. Answer is a clear cut *no*. See their code. – Hanky Panky Nov 13 '13 at 06:01
  • @Hanky웃Panky The answer is clear : You cannot bound class to function scope only. So I'm accepting this answer. – Bhojendra Rauniyar Nov 13 '13 at 06:09
  • You can accept this answer that's not a problem. But this answer does not work for your code. Whatever you tried to do in your code is simply impossible. In this solution there is no outer class that is why it works. – Hanky Panky Nov 13 '13 at 06:11
  • @Hanky웃Panky of course you are right. But the title of question is not match to code. resume: Inside function you can, inside method you cannot. – sectus Nov 13 '13 at 06:24
  • That's correct. Misunderstanding is only based on that difference. I went ahead answering based on their code and you answered based on their title. Both answers are correct then depending upon what the real situation is. +1 – Hanky Panky Nov 13 '13 at 06:26
1

You can not.

Run your code after removing those publics and you ll get this:

Fatal error: Class declarations may not be nested on line 6

Read 1

Read 2

Community
  • 1
  • 1
Hanky Panky
  • 46,730
  • 8
  • 72
  • 95