[英]Passing a variable into a protected function in PHP
我正在使用具有受保护功能的插件,例如
<?php
class CustomUploadHandler extends UploadHandler {
protected function get_user_id() {
//If I manually enter a value here, the value passes along
return ('myvariable');
}
}
?>
但是当我像
<?php $myvar = 'myvariable'; ?>
并尝试将其插入这样的功能
<?php
class CustomUploadHandler extends UploadHandler {
protected function get_user_id() {
//If I use a variable, the value is lost
return ($myvar);
}
}
?>
它完全失败...我不熟悉受保护的类以及return()
工作原理,因此将不胜感激。
我尝试了很多行代码,例如
print $myvar;
return $myvar;
echo $myvar;
有和没有()
不要通过global
关键字引入全局状态。 您会欣喜若狂。
而是在创建类时或使用setter将依赖项( 在这种情况下为值,用户ID )注入到类中。
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);
}
}
然后,当您具有此类的一个实例时:
// creates and sets $user_id = 42
$customUploadHandler = new CustomUploadHandler(42);
// sets $user_id = 77
$customUploadHandler->set_user_id(77);
Protected
意味着只有类本身,定义该函数的类的父类和子类才能使用该函数。 因此,这取决于调用函数的位置。 不带括号的return语句应该没问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.