【问题标题】:PHP Key=>Value array using Static::VariablesPHP Key=>Value 数组使用 Static::Variables
【发布时间】:2013-05-01 12:42:37
【问题描述】:

谁能告诉我为什么这段代码不起作用?这似乎是完成所提议任务的最有效方法,我不明白为什么我不断收到错误 - 即使我反转 KeyValue。

我正在尝试用 static::variables 替换文本字符串/数组中的#tags#,形成一个外部类。

错误:

Parse error: syntax error, unexpected T_VARIABLE, expecting T_STRING in /home/content/57/10764257/html/marketing/includes/ProcessEmail.class.php on line 5

外部类:

class MyClass {
    public static $firstName = "Bob";    // Initally set as "= null", assigned
    public static $lastName = "Smith";   // statically through a call from
}                                        // another PHP file.

主 PHP 文件:

// This is the array of find/replace strings

private static $tags = array("#fistName#", MyClass::$firstName,
                             "#lastName#", MyClass::$lastName);

// This jumps trough the above tags, and replaces each tag with
// the static variable from MyClass.class.php

public static function processTags($message) {

    foreach ($tags as $tag => $replace) {
        $message = str_replace($tag, $replace, $message);
    }

}

但我一直收到这个错误...?

谢谢!

【问题讨论】:

  • 把你的完整代码ProcessEmail.class.php。那么调试起来就很简单了。

标签: php arrays


【解决方案1】:

来自http://php.net/manual/en/language.oop5.static.php

与任何其他 PHP 静态变量一样,静态属性只能使用文字或常量进行初始化;不允许表达。因此,虽然您可以将静态属性初始化为整数或数组(例如),但您不能将其初始化为另一个变量、函数返回值或对象。

所以你不能使用MyClass::$firstName 作为静态属性的值。

另一种解决方案是使用const 而不是static。 (PHP > 5.3)

class MyClass {
    const firstName = "Bob";
    const lastName = "Smith";
}

class MyClass2 {
    public static $tags = array(
        'firstName' => MyClass::firstName,
        'LastName'  => MyClass::lastName
    );
}

print_r(MyClass2::$tags);

【讨论】:

  • 我想我明白你的意思了。如果它不是静态的,比如我实例化了 MyClass,它会起作用吗?
  • @Philly2NYC 不,那也行不通。但请参阅我的更新答案。
【解决方案2】:

尝试将您的代码替换为:

<?php 
class MyClass {
    private static $tags = array(
        '#firstName#' => 'Bob',
        '#lastName#'  => 'Smith'
    );

    public static function processTags(&$message) {
        foreach (self::$tags as $tag => $replace) {
            $message = str_replace($tag, $replace, $message);
        }
    }
}


$message = 'Hello, my name is #firstName# #lastName#';
MyClass::processTags($message);
echo($message);

结果:

Hello, my name is Bob Smith

【讨论】:

  • 等等,等一下,这不是我需要的 - 我正在替换更大的字符串/数组中的字符串 - 不是试图获取我的数组的值...
  • 不,就像@redreggae 提到的那样,抛出错误是因为您试图从您的类中访问静态变量。如果你想保留static 的东西,这是要走的路,否则你可以从$firstName$lastName 中删除static 关键字,实例化你的类并使用-&gt; 操作数访问这两个属性。
  • 没有做我需要的事情 - 最后,只需要重新编码...... PHP规则胜过常识......
猜你喜欢
  • 1970-01-01
  • 2014-04-23
  • 1970-01-01
  • 1970-01-01
  • 2015-01-22
  • 1970-01-01
  • 1970-01-01
  • 2012-03-05
  • 2017-02-01
相关资源
最近更新 更多