3

Is there anyway to create public or private or protected classes in a namespace just like java?

like...

namespace foo; public class Account { ....... } private class PrivateAccount { ....... } 

please let me know if there is any workaround to do this in PHP.

3
  • 1
    Could you explain how you want to use private classes? Why impose this restriction? Remember that PHP is also a dynamically typed language so you don't have much freedom to impose restrictions on type automatically, except by manual checking. Likewise you could manually restrict the constructor (by passing some special string or something ugly like that) but there isn't much point. Commented Feb 8, 2012 at 11:21
  • I want to restrict the class usage to only inside the namespace. at least I want to throw an error, if I try to create instance of this class outside of this namespace. Commented Feb 8, 2012 at 11:29
  • Perhaps I should reiterate. Why impose this restriction? You can't easily impose the same level of rigour in a dynamically typed language as you can in a strongly typed language. Your best bet is writing good documentation and structuring your code so it's obvious which classes should not really be messed with. Commented Feb 8, 2012 at 11:32

2 Answers 2

4

No, classes in PHP may not be anything but public and that is declared implicitly. From the PHP docs on classes in PHP5:

Basic class definitions begin with the keyword class, followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class.

Putting a visibility keyword in front of the class will likely result in a fatal error.

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

Comments

2

Typically what you do is declare the constructor of the class private. Then you can create a separate static function in the class that will do some checks (i.e. check the namespace) and conditionally return an instance of the class by calling the private constructor. This is also typically how you implement singletons.

1 Comment

You can prevent initialisation like this (as you say identically to implementing a singleton) but this doesn't prevent the object instance being passed outside the scope of the namespace.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.