【问题标题】:how to use a php variable from other php script in a function()如何在函数()中使用来自其他 php 脚本的 php 变量
【发布时间】:2012-04-12 15:58:13
【问题描述】:

我已经搜索了 stackoverflow 和其他一些网站,并尝试了几个小时的新代码组合,但我放弃了.. 我有 2 个 php 文件,一个名为 getimages.php,另一个名为 mod_slidepluslight.php 我使用 Joomla 作为 CMS,并使用灯箱制作了幻灯片模块,现在我想通过设置的模块参数从 Joomla 中的文件夹中检索图像.xml 文件。我通过使用以下代码做到了这一点:

$imagePath = $params->get('imagePath', 'banners');

现在,当我尝试声明这个变量并在我的代码中使用它时,它什么也没做。

function returnimages($relPath = "/KVD/images/") { 
$dirname = $_SERVER['DOCUMENT_ROOT'] . $relPath . $imagePath; 

$imagePath 应该添加在 /KVD/images/......./ 之后或现在的位置。 getimages.php 的整个代码如下所示:

Header("content-type: application/x-javascript");

$imagePath = $params->get('imagePath', 'banners/');

function returnimages($relPath = "/KVD/images/") { 
$dirname = $_SERVER['DOCUMENT_ROOT'] . $relPath . $imagePath; 
$files = array(); 
$curimage = 0; 
if($handle = opendir($dirname)) { 
while(false !== ($file = readdir($handle))){ 
if (preg_match('/\.(jpg|jpeg|gif|png)$/', $file)){ 
print_r ('galleryarray['.$curimage.']="'. $relPath . $file .'";'); 
$curimage++; 
} 
} 

closedir($handle); 
} 
return($files); 
} 

print 'var galleryarray=new Array();'; //Define array in JavaScript 
returnimages() //Output the array elements containing the image file names

谢谢,科恩。

【问题讨论】:

    标签: php variables joomla include scope


    【解决方案1】:

    yoo 在函数内调用 $imagePath 但 $imagePath 超出函数范围!您可以将 $imagePath 作为参数发送给函数

    【讨论】:

    • 感谢您的回答,您的意思是我应该在我的函数中添加我的 $imagePath =....?
    • 这是一个可能的解决方案。另一个定义这样的函数: function returnimages($relPath = "/KVD/images/", $imagePath) 然后当你调用它时 returnimages(null, $imagePath)
    【解决方案2】:

    请记住变量的范围:您的 returnimages() 函数将无法访问 $imagePath 变量,除非您将其全球化或通过函数传递它。

    只需在功能代码的顶部添加:

    global $imagePath;
    

    【讨论】:

    • 嘿,谢谢你的回答,我现在设置的是这种方式,但它仍然无法正常工作。 $imagePath = $params->get('imagePath', 'banners/');函数 returnimages($relPath = "/KVD/images/") { 全局 $imagePath; $dirname = $_SERVER['DOCUMENT_ROOT'] 。 $relPath 。 $imagePath;
    【解决方案3】:

    您需要考虑不同的方法。当创建一个将使用另一个脚本的模块时,这个另一个脚本应该是一个帮助器。

    看看:

    http://docs.joomla.org/Creating_a_Hello_World_Module_for_Joomla_1.5

    如果您将 getimages.php 的内容作为帮助程序提供,如上面链接中所述,您将能够在该脚本中使用您的参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-02
      • 1970-01-01
      • 2023-01-14
      • 1970-01-01
      • 1970-01-01
      • 2013-11-25
      • 1970-01-01
      • 2021-07-29
      相关资源
      最近更新 更多