【问题标题】:Function Passing array to defined key函数将数组传递给定义的键
【发布时间】:2012-09-28 06:25:27
【问题描述】:

我创建了一个函数来获取我的帖子缩略图和后备图片。

<?php
function png_thumb($class=null,$thumbsize=null,$no_thumb,$imgclass=null,$extras=null,$hover_content=null){

    $title_attr = array(
        'title' => get_the_title(),
        'alt' => get_the_title(),
        'class' => $imgclass
    );  ?>


    <div class="<?php echo $class ?>">
        <a href="<?php the_permalink(); ?>" title="<?php //the_title(); ?>">
            <?php if ( has_post_thumbnail() ) {
                the_post_thumbnail($thumbsize, $title_attr);
            } else { ?>
                <img src="<?php bloginfo('template_directory'); ?>/images/<?php echo $no_thumb ?>" alt="<?php the_title(); ?>" class="<?php echo $imgclass; ?>" <?php echo $extras; ?> />
            <?php } ?>                          
        </a>
        <?php if($hover_content != "") { ?>
        <a href="<?php the_permalink(); ?>"><div class="hovereffect"><?php echo $hover_content; ?></div></a>
        <?php } ?>
    </div>

<?php } ?>

但我相信传递数组会比这更好。但我不知道如何创建可以通过预定义键传递的函数。与 $title_attr 分配的数组()相同。或者 wordpress $args 是如何工作的。

【问题讨论】:

    标签: php arrays wordpress function


    【解决方案1】:

    “使用预定义键传递数组”不是 PHP 理解的概念。不过,您可以简单地这样做:

    function png_thumb(array $args = array()) {
        $args += array('class' => null, 'thumbsize' => null, 'no_thumb' => null, 'imgclass' => null, 'extras' => null, 'hover_content' => null);
    
        echo $args['class'];
        ...
    

    此函数接受一个数组并使用默认值填充所有未传递的键。你像这样使用它:

    png_thumb(array('thumbsize' => 42, ...));
    

    【讨论】:

    • 但是如何将这些键值分配到适当的地方?
    • “适当的地方”是什么意思?
    • 我的意思是如果我通过键 nothumb abnd 我想在一个特定区域使用该值。我该如何分配?我从来没有让数组的函数如此混乱
    • Sheikh Heera 的回答很有效,非常适合我的功能,因为它已经在使用了。但是,我发现您的答案也非常有用和合适,因此投票赞成。非常感谢您的帮助和努力。
    【解决方案2】:

    你也可以试试这个

    function png_thumb($args=array()) {
        $default= array('class' => null, 'thumbsize' => null, 'no_thumb' => null, 'imgclass' => null, 'extras' => null, 'hover_content' => null);
        $settings=array_merge($default,$args);
        extract($settings); // now you can use variables directly as $class, $thumbsize etc, i.e
        echo $class; // available as variable instead of $settings['class']
        echo $thumbsize; // available as variable instead of $settings['thumbsize']
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-13
      • 2016-07-16
      • 1970-01-01
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多