1

下面是两个示例 PHP 函数:

function myimage1() {
global $post;
    $attachment_id = get_post_meta($post->ID, 'f1image', $single = true);
    $myimage1 = wp_get_attachment_image( $attachment_id, thumbnail );
return $myimage1;
}

(我这样称呼它<?php echo myimage1(); ?>:)

function myimage2() {
global $post;
    $attachment_id = get_post_meta($post->ID, 'f1image', $single = true);
    $myimage2 = wp_get_attachment_image( $attachment_id, medium );
return $myimage2;
}

(我这样称呼它<?php echo myimage2(); ?>:)

如您所见,两者都有一个共同的变量$attachment_id。而且这两个函数有很大的关系,只是我不知道如何将它们结合起来,或者如何从组合函数中调用它们。

PS:我不懂 PHP,我的术语可能有点模糊。在这种情况下,请随时纠正我。

4

2 回答 2

2
function myimage($level) {
    global $post;
    $attachment_id = get_post_meta($post->ID, 'f1image', true);
    $myimage = wp_get_attachment_image( $attachment_id, $level );
    return $myimage;
}

myimage("medium");
myimage("thumbnail");
于 2012-05-05T08:30:47.250 回答
0

OOP 正是为了满足这种需求。两个函数(方法)使用相同的类变量。

<?php

class A {

    public $attachment_id;

    private function wp_get_attachment_image() {

        // place your wp_get_attachment_image() function content here

    }

    public function myimage1() {

        $myimage1 = $this->wp_get_attachment_image($this->attachment_id, medium);
        return $myimage1;

    }

    public function myimage2() {

        $myimage2 = $this->wp_get_attachment_image($this->attachment_id, medium);
        return $myimage2;

    }

}

$a = new A;
$a->attachment_id = $a->get_post_meta($post->ID, 'f1image', $single = true);
$a->myimage1();
$a->myimage2();

?>
于 2012-05-05T08:38:00.617 回答