Plugins Wordpress插件/自定义类/获取选项()/shortcode

Plugins Wordpress插件/自定义类/获取选项()/shortcode,plugins,wordpress,Plugins,Wordpress,当使用短代码时,我在显示插件文件中定义的自定义类返回的信息时遇到了一个问题。我会写一些模拟文件来展示我的问题 /wp content/plugins/my plugin/classes/my_class.php <?php class People { public $api_url = "https://www.external-service.com/api"; private $api_key; function __construct($key = null) {

当使用短代码时,我在显示插件文件中定义的自定义类返回的信息时遇到了一个问题。我会写一些模拟文件来展示我的问题

/wp content/plugins/my plugin/classes/my_class.php

<?php
class People {
  public $api_url = "https://www.external-service.com/api";
  private $api_key;

  function __construct($key = null) {
    if $(key) {
      $this->api_key = $key;
    }

  function get_response() {
    $path = $this->api_url . "?my_api_token=" . $this->api_key;
  }
}
?>
<?php
/**
* all of the wordpress plugin comments
* ...
*/

require "myplg_options.php";
require "myplg_shortcodes.php";
<?php
require "classes/my_class.php";

$options = get_option('myplg_settings');
$myplg = new People($options['myplg_api_key']);
$response = $myplg->get_response();

function myplg_list_result(){
  echo "the shortcode is working!";
  var_dump($options, $myplg, $respnose);
}
add_shortcode('myplg_list', 'myplg_list_result');
?>

/wp content/plugins/my plugin/my plugin.php

<?php
class People {
  public $api_url = "https://www.external-service.com/api";
  private $api_key;

  function __construct($key = null) {
    if $(key) {
      $this->api_key = $key;
    }

  function get_response() {
    $path = $this->api_url . "?my_api_token=" . $this->api_key;
  }
}
?>
<?php
/**
* all of the wordpress plugin comments
* ...
*/

require "myplg_options.php";
require "myplg_shortcodes.php";
<?php
require "classes/my_class.php";

$options = get_option('myplg_settings');
$myplg = new People($options['myplg_api_key']);
$response = $myplg->get_response();

function myplg_list_result(){
  echo "the shortcode is working!";
  var_dump($options, $myplg, $respnose);
}
add_shortcode('myplg_list', 'myplg_list_result');
?>

如注释中所述,这是因为变量是函数作用域。使用闭包可能会更好

<?php
require "classes/my_class.php";

$options = get_option('myplg_settings');
$myplg = new People($options['myplg_api_key']);
$response = $myplg->get_response();
add_shortcode('myplg_list', function() use ($options, $response, $myplg) {
    echo "the shortcode is working!";
    var_dump($options, $myplg, $respnose);
});
这是因为。您应该添加
global$options、$myplg、$respnose
位于myplg\u list\u result()的顶部,但使用全局变量是不安全的,因为它们可以在任何脚本的任何位置更改。如果不想重新实例化,可以使用。