【问题标题】:How to make PHP variables accessible in different files?如何使 PHP 变量可以在不同的文件中访问?
【发布时间】:2021-02-12 18:38:09
【问题描述】:

我正在开发一个 WordPress 网站。我想知道如何共享多个不同文件中需要的一些 PHP 变量,而无需一遍又一遍地复制粘贴相同的变量。

我有一些分类变量需要在不同的文件中使用。

这是来自我的 single.php 文件:

$taxonomy_themes    = wp_get_post_terms(get_the_ID(), 'themas');
$taxonomy_rubrieken = wp_get_post_terms(get_the_ID(), 'rubrieken');

$taxonomy_themes_singular_name    = $taxonomy_themes[0]->name;
$taxonomy_rubrieken_singular_name = $taxonomy_rubrieken[0]->name;
    
$taxonomy_themes_singular_slug    =  $taxonomy_themes[0]->slug;
$taxonomy_rubrieken_singular_slug =  $taxonomy_rubrieken[0]->slug;
    
$taxonomy_themes_singular_link    = get_term_link($taxonomy_themes_singular_slug, 'themas');
$taxonomy_rubrieken_singular_link = get_term_link($taxonomy_rubrieken_singular_slug, 'rubrieken');

如何与其他文件全局共享这些文件并使用它们?

【问题讨论】:

标签: php wordpress


【解决方案1】:

您可以使用 php $GLOBALS 方法将它们定义为全局变量,该函数的文档可在 here 获得

虽然可以定义资源常量,但不建议这样做,这可能会导致不可预知的行为。

为你编码

$taxonomy_themes    = wp_get_post_terms(get_the_ID(), 'themas');
$taxonomy_rubrieken = wp_get_post_terms(get_the_ID(), 'rubrieken');

$taxonomy_themes_singular_name    = $taxonomy_themes[0]->name;
$taxonomy_rubrieken_singular_name = $taxonomy_rubrieken[0]->name;
    
$taxonomy_themes_singular_slug    =  $taxonomy_themes[0]->slug;
$taxonomy_rubrieken_singular_slug =  $taxonomy_rubrieken[0]->slug;
    
$taxonomy_themes_singular_link    = get_term_link($taxonomy_themes_singular_slug, 'themas');
$taxonomy_rubrieken_singular_link = get_term_link($taxonomy_rubrieken_singular_slug, 'rubrieken');

 $GLOBALS['taxonomy_rubrieken_singular_link'] =  $taxonomy_rubrieken_singular_link;

// use the variable => without the dollar sign taxonomy_rubrieken_singular_link
var_dump($GLOBALS['taxonomy_rubrieken_singular_link']);

【讨论】:

  • 我明白了:常量只能计算为标量值、数组或资源
  • 尝试使用 $GLOBAL,如果它不起作用,我建议创建一个类并将变量定义为类的构造函数中的静态属性
猜你喜欢
  • 2019-10-06
  • 2018-11-16
  • 2016-07-05
  • 1970-01-01
  • 2015-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多