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{
     .....
    }
  }
}
3
  • Did you try it? You'll get to know what it does Commented Nov 13, 2013 at 5:56
  • Why do you want to do this? The class can be dynamically created but it won't be scoped to that function only Commented Nov 13, 2013 at 5:59
  • The question not match to the code. Commented Nov 13, 2013 at 6:00

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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 The answer is clear : You cannot bound class to function scope only. So I'm accepting this answer.
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 of course you are right. But the title of question is not match to code. resume: Inside function you can, inside method you cannot.
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
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.