开发者

Private functions can be called publicly if the object is instantiated within the same class

<?php
 //5.2.6
class Sample {
    private function PrivateBar() {
      echo 'private called<br />';
    }

    public static function StaticFoo() {
      echo 'static called<br />';
      $y = new Sample();
      $y->PrivateBar();
    }
 }

 Sample::StaticFoo();
?>

The above code will output:

"static called
 private called"

Why does $y->PrivateBar(); not throw an error? It is a private function after all.

What is the object oriented design logic behind this? Is this uniq开发者_如何学Pythonue to PHP, or is this standard OOP?


Because StaticFoo, though static, is still considered part of the Sample class.

This is also reproducable in C#:

public class Sample
{
    private void PrivateBar()
    {
        Console.WriteLine("private called\r\n");
    }

    public static void StaticFoo()
    {
        Console.WriteLine("static called\r\n");
        Sample y = new Sample();
        y.PrivateBar();
    }
}

class Program
{
    static void Main(string[] args)
    {
        Sample.StaticFoo();
        Console.Read();
    }
}

With the output:

static called

private called


Why does $y->PrivateBar(); not throw an error? It is a private function after all.

Private function do not throw an error when you use them inside the class, they throw the error when accessed out side of the class.

What is the object oriented design logic behind this? Is this unique to PHP, or is this standard OOP?

It is not unique to PHP and is standard OOP.


Actually you are calling the private method with in the class, So that it does not throw error.

If you do the same thing out of the class , It will throw the error.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜