【问题标题】:call a variable in a static function to another static function from same class in php将静态函数中的变量调用到php中同一类的另一个静态函数
【发布时间】:2018-05-03 14:23:28
【问题描述】:

我有一个包含几个静态函数的类。我的一个函数构建了一个变量,我想在另一个静态函数中使用该变量。

如何调用该变量?

class MyClass{
    public static function show_preprice_value_column( $column, $post_id ) {
        if ( $column == 'product_preprice' ) {
            $product_preprice = get_post_meta( $post_id, 'product_preprice', true );
            if ( intval( $product_preprice ) > 0 ) {
                echo $product_preprice;
            }
        }
    }

    public static function show_off_value_column( $column, $post_id ) {
        if ( $column == 'product_off' ) {
            var_dump((int)self::show_preprice_value_column());
        }
    }
}

【问题讨论】:

  • 你想在哪里使用哪个变量?
  • @AndrewSchultz 我想在 show_off_value_column 函数中使用 $product_preprice

标签: php wordpress variables call


【解决方案1】:

你是这个意思吗?

<?php
class MyClass
{

    private static $var;

    public static function funcA()
    {
        self::$var = "a";
    }

    public static function funcB()
    {
        self::$var = "b";
    }

}

【讨论】:

  • 我想在funcB()中使用一个变量
  • 添加:私有静态 $product_preprice;到你的班级顶部并像这样调用变量:self::$product_preprice
  • 你不能将funcA()中声明的变量传递给funcB(),但是你可以使用类成员来共享变量,就像我上面刚刚做的那样。
【解决方案2】:

我使用了这个代码:

class Test {
    public static function test1(){
        return 12;
    }

    public static function test2(){
        $var = self::test1();
        echo $var;
        echo "\n".gettype($var);
    }
} 

Test::test2();

得到这个结果:

12
integer

所以你需要在echo 之后使用return 来传达价值

【讨论】:

    猜你喜欢
    • 2014-10-28
    • 1970-01-01
    • 1970-01-01
    • 2011-10-03
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多