首页 > 解决方案 > 如何为数组内的值创建常量并在php中的类外部访问它们

问题描述

我已经使用常量在一个类中创建了数组,并通过键、值对为该数组分配了值,所以我想为 a 创建 const,为 b 创建 const,为 c 值创建 const,那么如何创建它并访问这些值(a, b,c) 课外使用 Php?实际上我没有得到任何输出。

<?php  

class foo {

    const arrayOfvalues = [
        'a' => 'text for  a',
        'b' => 'text for b',
        'c' => 'text for c'

    ]; 
    const for_avalue= foo::arrayOfvalues[0];  //create constant for a
    const for_bvalue= foo::arrayOfvalues[0];  //create constant for b
    const for_cvalue= foo::arrayOfvalues[0];  //create constant for c

}
echo 'current const value'. for_avalue;  //call a value by its constant name

?>

标签: php

解决方案


您忘记使用正确的indexes并且还调用class. 尽管我不明白您为什么要以这种方式创建常量,但您的当前代码的正确版本如下:

class foo {

    const arrayOfvalues = [
        'a' => 'text for  a',
        'b' => 'text for b',
        'c' => 'text for c'

    ]; 
    const for_avalue= foo::arrayOfvalues['a'];  //create constant for a
    const for_bvalue= foo::arrayOfvalues['b'];  //create constant for b
    const for_cvalue= foo::arrayOfvalues['c'];  //create constant for c

}
echo 'current const value'. foo::for_avalue;

推荐阅读