VIDesignz
VIDesignz

Reputation: 4783

Passing a variable into a protected function in PHP

I am working with a plugin where there is a protected function like so

<?php

class CustomUploadHandler extends UploadHandler {

protected function get_user_id() {

              //If I manually enter a value here, the value passes along
      return ('myvariable'); 

   }
 }

?>

Yet when I make a variable like

<?php  $myvar = 'myvariable';  ?>

and try to insert it into the function like this

<?php

class CustomUploadHandler extends UploadHandler {

protected function get_user_id() {

              //If I use a variable, the value is lost
      return ($myvar); 

   }
 }

?>

it completely fails... I am unfamiliar with protected classes and also how return() works so any help would be greatly appreciated.

I have tried many lines of code such as

print $myvar; return $myvar; echo $myvar; with and without ()

Upvotes: 0

Views: 2596

Answers (2)

Dan Lugg
Dan Lugg

Reputation: 20592

Don't introduce global state via the global keyword. You'll be welcoming a world of pain down the line.

Instead, inject the dependency (the value, a user ID in this case) into the class when it's created, or with a setter.

class CustomUploadHandler extends UploadHandler
{

    private $user_id;

    protected function get_user_id()
    {
        return $this->user_id;
    }

    // setter injection; the value is
    // passed via the method when called
    // at any time
    public function set_user_id($user_id)
    {
        $this->user_id = $user_id;
    }

    // constructor injection; the value is
    // passed via the constructor when a new
    // instance is created
    public function __construct($user_id)
    {
        $this->set_user_id($user_id);
    }

}

Then when you have an instance of this class:

// creates and sets $user_id = 42
$customUploadHandler = new CustomUploadHandler(42);

// sets $user_id = 77
$customUploadHandler->set_user_id(77);

Upvotes: 6

malifa
malifa

Reputation: 8165

Protected means that only the class itself, the parent class and the childs of the class where the function is defined can use the function. So it depends from where you call the function for it to work. return statements without brackets should be fine.

Upvotes: 0

Related Questions