tags:

views:

25

answers:

3
<?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 unique to PHP, or is this standard OOP?

A: 

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.

pavun_cool
+1  A: 

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.

Sarfraz
Why down vote....................?
Sarfraz
$this is null in a static function.
McAden
@McAden: hmmm, fixed anyways, modified the answer, thanks...
Sarfraz
you changed your answer to a valid one, undid downvote
McAden
@McAden: thanks for that :)
Sarfraz
+1  A: 

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
McAden