0

So , I'm new to PHP and I know this is an easy question for a lot of you , but I'm not sure about one thing.

If I have this , the new object $a and $d can't echo the function foo() , because it's protected , so it means that only sub classes can use it , OBJECT can't? It's a bit confusing for me.

Sorry if it's a stupid question , but I don't have a php friend to ask this.

<?php

    class A {
        protected function foo(){
            echo "AAA";
        }
    }

    class D extends A { }

    $a = new A();
    $d = new D();
    $a->foo();
    $d->foo();
?>
LF00
  • 27,015
  • 29
  • 156
  • 295
  • 1
    It can only be called from within the class that owns it or a class that extends it. Private functions can be called only from within the class that owns it. Public functions can be called globally like you are trying to do above – Brian McCall Mar 14 '17 at 15:38
  • 1
    Suggested read: http://php.net/manual/en/language.oop5.visibility.php – Pieter van den Ham Mar 14 '17 at 15:38

2 Answers2

0

because it's protected , so it means that only sub classes can use it , OBJECT can't?

object is instance of class. These are NOT equivalent.

For your question - only public methods are reachable from outside. So you cannot $d->foo() but i.e. D class can have public method x() which would just do $this->foo() and that would work as x is part of the class, so it's allowed to reach protected element.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
0

Check this. This is how it will wwork.

class A {
    protected function foo(){
        echo "AAA";
    }
}

class D extends A {
    public function foo2() {
        $a = new A();
        $a->foo();
    }
 }

//$a = new A();
$d = new D();
//$a->foo();
$d->foo2();
PayPal_Kartik
  • 226
  • 2
  • 9