Search code examples
phpclassvariablesmemberprotected

Accessing a protected member variable outside a class


I'm querying for the ID of a field by accessing a class function which someone has already put in place. The result is a object returned with protected member variables. I'm struggling to see how I can access the member variable values outside the class.


Solution

  • Just add a "get" method to the class.

    class Foo
    {
        protected $bar = 'Hello World!';
    
        public function getBar()
        {
            return $this->bar;
        }
    }
    
    $baz = new Foo();
    
    echo $baz->getBar();