在不使用变量的情况下重写PHP代码


Rewrite PHP code without using variables

示例PHP代码:

<?php 
    $image_attributes = wp_get_attachment_image_src( '8' );
?> 
 
<img src="<?php echo $image_attributes[0]; ?>" width="<?php echo $image_attributes[1]; ?>" height="<?php echo $image_attributes[2]; ?>">

现在,比方说,我根本不想使用$image_attributes变量,稍后使用img标记直接使用wp_get_attachment_image_src( '8' );而不是$image_attributes[0];$image_attributes[1];$image_attributes[2];

在这种情况下,我应该如何修改代码?

为什么

让我举例说明(我的真实用例)。

<?php 
    $attachment_attributes = wp_get_attachment_image_src( '8' ); // returns an array
?> 
 
<media:content url="<?php echo $attachment_attributes[0]; ?>" width="<?php echo $attachment_attributes[1]; ?>" height="<?php echo $attachment_attributes[2]; ?>" type="image/jpeg">

我该如何做同样的事情,比如当我这样编码的时候?

foreach ( $attachments as $att_id => $attachment ) {
    $attachment_attributes = wp_get_attachment_image_src( '8' );
    
    // Should it be done like this? If not, how do I do it?
    $output .= '<media:content height="' . $attachment_attributes[0]; . '" type="image/jpeg">';
    if ( $captiontag && trim($attachment->post_excerpt) ) {
        $output .= "
            <{$captiontag}>" . wptexturize($attachment->post_excerpt) . "</{$captiontag}>";
    }
    $output .= '
        </media:content>';
}

不确定为什么你试图避免变量,但你可能会逃脱这样的惩罚:

<?php
vprintf(
    '<img src="%s" width="%d" height="%d">',
    wp_get_attachment_image_src( '8' )
);

或者,从"为什么"的代码

<?php
foreach ( $attachments as $att_id => $attachment ) {
    $attachment_attributes = wp_get_attachment_image_src( '8' );
    $output .= '
        <media:content
          url="' . $attachment_attributes[0] . '"
          width="' . $attachment_attributes[1] . '"
          height="' . $attachment_attributes[2] . '"
          type="image/jpeg">';
    if ( $captiontag && trim($attachment->post_excerpt) ) {
        $output .= "
            <{$captiontag}>" . wptexturize($attachment->post_excerpt) . "</{$captiontag}>";
    }
    $output .= '
        </media:content>';
}