开发者

Is it possible to create nested classes in PHP as it is in C#?

开发者 https://www.devze.com 2023-02-04 13:25 出处:网络
In C# you can have nested classes like this, which are useful if you have classes which do not have meaning outside the scope of one particular class, e.g. in a factory pattern:

In C# you can have nested classes like this, which are useful if you have classes which do not have meaning outside the scope of one particular class, e.g. in a factory pattern:

public abstract class BankAccount
{
  private BankAccount() {} 
  private sealed class SavingsAccount : Bank开发者_Go百科Account { ... }
  private sealed class CheckingAccount : BankAccount { ... }
  public BankAccount MakeSavingAccount() { ... }
  public BankAccount MakeCheckingAccount() { ... }
}

Is this possible in PHP?

I've read that it was planned for PHP 5, then cancelled, then planned again, but can't find definitive info.

Does anyone know how to create nested classes (classes within the scope of another class) as in the above C# example using PHP 5.3?


No, this isn't possible in PHP. Classes must inhabit the global namespace; the best you can do is just pretend they don't exist in all of your other code.

This kind of thing is common in PHP; for example, PHP lacks static initializers, so if you want to eagerly initialize the static members of a class, it must be done by calling a public method from outside the class. Ugly.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号