In terms of usage, what is the difference between a private function and a security class?

I know the manual definition, but in terms of the real use of life, what's the difference? When will you use one over the other?

+3
source share
2 answers

When you know that a variable will be used only in this class, and not in any other or expanding class, you would call it private. Therefore, if you extend the class and mistakenly name the variable as a private name, this will give you an error and thus allow you to make a mistake.

, , -, , , ( ), , , , .

, .

+2

EDIT: , ( ( ) ), .

PHP

private , , /.

, / .

.

<?php
/**
 * Define MyClass
 */
class MyClass
{
    public $public = 'Public';
    protected $protected = 'Protected';
    private $private = 'Private';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private


/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    // We can redeclare the public and protected method, but not private
    protected $protected = 'Protected2';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj2 = new MyClass2();
echo $obj2->public; // Works
echo $obj2->private; // Undefined
echo $obj2->protected; // Fatal Error
$obj2->printHello(); // Shows Public, Protected2, Undefined

?>
+3

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


All Articles