将两个不同的 PHP 函数与相同的变量子集组合在一起


Combine two different PHP functions with the same subset of variables?

下面是两个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,我的术语可能有点模糊。在这种情况下,请随时纠正我。

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");

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();
?>