php - 如何在类中调用全局对象函数,出现“未定义变量”错误
问题描述
我正在创建这个简单的 PHP,试图使用 Predis 库在 Redis 上缓存请求,我在类外部实例化了我的 $redis 对象,我需要从类函数内部调用它。但是我不断收到未定义的变量:redis 消息。
我已经尝试在类范围内外调用我的缓存验证函数。
这是代码:
<?php
require "predis/src/Autoloader.php";
Predis\Autoloader::register();
global $redis;
$redis = new Predis\Client();
class SimpleJsonRequest
{
private $redisLocal;
public function __construct() {
global $redis;
$this->redisLocal =& $redis;
}
private static function makeRequest(string $method, string $url, array $parameters = null, array $data = null)
{
$opts = [
'http' => [
'method' => $method,
'header' => 'Content-type: application/json',
'content' => $data ? json_encode($data) : null
]
];
$url .= ($parameters ? '?' . http_build_query($parameters) : '');
return file_get_contents($url, false, stream_context_create($opts));
}
public static function get(string $url, array $parameters = null)
{
if(validateCache('GET', $url, $parameters))
return json_decode(self::makeRequest('GET', $url, $parameters));
}
public static function post(string $url, array $parameters = null, array $data)
{
if(validateCache('POST', $url, $parameters, $data))
return json_decode(self::makeRequest('POST', $url, $parameters, $data));
}
public static function put(string $url, array $parameters = null, array $data)
{
if(validateCache('PUT', $url, $parameters, $data))
return json_decode(self::makeRequest('PUT', $url, $parameters, $data));
}
public static function patch(string $url, array $parameters = null, array $data)
{
if(validateCache('PATCH', $url, $parameters, $data))
return json_decode(self::makeRequest('PATCH', $url, $parameters, $data));
}
public static function delete(string $url, array $parameters = null, array $data = null)
{
if(validateCache('DELETE', $url, $parameters, $data))
return json_decode(self::makeRequest('DELETE', $url, $parameters, $data));
}
}
function validateCache(string $method, string $url, array $parameters = null, array $data = null)
{
if($redis->exists($method)
&& $redis->get($method, 'url') == $url
&& json_decode($redis->get($method, 'parameters')) == $parameters
&& json_decode($redis->get($method, 'data')) == $data)
{
echo'request cached';
return false;
}
else
{
$redis->hMset($method, [
'url' => $url,
'parameters' => $parameters = null ? null : json_encode($parameters),
'data' => $data = null ? null : json_encode($data)
]);
$redis->expire($method, 10);
echo 'not cached';
return true;
}
}
$test = new SimpleJsonRequest();
print_r($redis);
echo $test->get('1');
echo $test->get('1');
我希望它首先打印“未缓存”,然后是“请求缓存”,但我不断收到未定义变量错误。
解决方案
您的validateCache
函数在$redis
没有首先将其声明为全局变量的情况下进行引用,就像您在SimpleJsonRequest
构造函数中所做的那样。
推荐阅读
- python - 根据键值删除日期在所需日期点之前的行
- powershell - 在詹金斯管道中不同代理的PS阶段之间传递变量
- aws-glue - 如何在 aws 胶水中进行模式演变?
- javascript - Javascript - 返回返回函数的值
- java - Spring 4:在应用程序上下文刷新之前运行一些初始化代码
- maven - 无法解析项目 spmf ca.pfv pom.xml 的依赖关系
- c++ - 在 C++ 中使用基于范围的循环显示地址
- docker - 将服务/进程绑定到接口,以防在 docker 中暴露它
- c# - c# 两个 ViewModel 之间的 Prism 连接
- python - Python列表索引超出范围但不应该