Private functions can be publicly published if the object is created in one 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 outputs:

"static called
 private called"

Why $ y-> PrivateBar (); don't throw a mistake? This is a private function.

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

+3
source share
3 answers

Since StaticFoo, although static, is still considered part of the Sample class.

This can also be reproduced 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 an exit:

static called

private called
+1
source

Why $ y-> PrivateBar (); don't throw a mistake? This is a private function in the end.

A private function does not throw errors when using them inside a class, they cause an error when accessing the side of the class.

- ? PHP, ?

PHP .

+1

In fact, you are calling a private method in the class so that it does not throw an error.

If you do the same from the class, it will throw an error.

0
source

Source: https://habr.com/ru/post/1735371/


All Articles