【问题标题】:How can use switch case statement using class names as case in php?如何在 php 中使用类名作为 case 的 switch case 语句?
【发布时间】:2014-08-25 13:40:37
【问题描述】:

有没有办法在下面的例子中使用类名作为案例? (伪代码)

class Some_Class {

    static function get_image_size() {

        switch (get_class($image_size)) {

            case 'Class_1':
                        $image_size = 'related-post';
                        break;
                    }
            case 'Class_2':
                        $image_size = 'full';
                        break;
                    }                   

                        return $image_size;

                    }

}

我需要这个来从不同的 php 类中调用一个特定的变量。 基本上我需要类似下面的代码,但使用 switch 语句:

class Some_class {

    static function get_image_size() {

        if Class_Name_1 {
            $image_size = 'related-post';
        }

        elseif Class_Name_2 {
            $image_size = 'full';
        }                   

        return $image_size;

    }

}

谢谢。

【问题讨论】:

  • 有点不清楚你想要什么。最佳猜测:switch (get_class($image_size))...?!
  • 查看更新的问题内容。谢谢。
  • 如果什么 Class_Name_1...?!仍然没有多大意义。

标签: php class switch-statement case


【解决方案1】:

好的,首先,如果这个“类名”是你调用这个函数的类的名字,为什么不把它作为一个变量传递给这个静态函数呢?

其次,如果类名是指“Some_Class”的名称,则可以通过静态函数中的此代码访问该名称:

$thisClassName = get_class(new self());

!更好:

$thisClassName = get_class();

$thisClassName = __CLASS__;

【讨论】:

  • 你不需要创建一个类的实例来获取它的类名。只需使用__CLASS__get_class()
猜你喜欢
  • 1970-01-01
  • 2014-01-06
  • 1970-01-01
  • 2014-08-05
  • 2017-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多