3

我想在PHPExcel_Cell_DefaultValueBinder::dataTypeForValue()不接触 PHPExcel 库的情况下覆盖该方法,这样以后升级库就不会出现问题。

事实上,我这样做是为了解决将数字转换为字符串的问题,我只是想知道如何覆盖一个方法,以便我可以继续使用该库而不会出现任何问题。

4

3 回答 3

4

您可以创建一个继承自的新类PHPExcel_Cell_DefaultValueBinder,并覆盖该函数dataTypeForValue

<?php
class PHPExcel_Cell_MyValueBinder extends PHPExcel_Cell_DefaultValueBinder {

    public static function dataTypeForValue($pValue = null) {
        if (/* your condition */) {
            // if you want to return a value, and i guess it's what you want, you can
            return PHPExcel_Cell_DataType::YOUR_TYPE;
        }
        // you call the fonction PHPExcel_Cell_DefaultValueBinder::dataTypeForValue();
        // so the already existant conditions are still working.
        return parent::dataTypeForValue($pValue);
    }

}
?>

之后,只需在代码顶部使用PHPExcel_Cell_MyValueBinder而不是使用:PHPExcel_Cell_DefaultValueBinder

PHPExcel_Cell::setValueBinder(new PHPExcel_Cell_MyValueBinder());

所以PHPExcel将使用你自己的 ValueBinder 来完成其余的执行:)

于 2012-09-17T13:07:11.137 回答
4
class PHPExcel_Cell_MyValueBinder extends PHPExcel_Cell_DefaultValueBinder implements PHPExcel_Cell_IValueBinder
{
    public function bindValue(PHPExcel_Cell $cell, $value = null)
    {
        // sanitize UTF-8 strings
        if (is_string($value)) {
            $value = PHPExcel_Shared_String::SanitizeUTF8($value);
        }

        // Implement your own override logic
        if (is_string($value) && $value[0] == '0') {
            $cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_STRING);
            return true;
        }

        // Not bound yet? Use default value parent...
        return parent::bindValue($cell, $value);
    }
}
于 2012-09-17T13:11:35.227 回答
3

您可以扩展类并覆盖您希望扩展其功能的方法。这遵循了SOLID 编程的开放/封闭原则(对扩展开放但对修改封闭),您无需对 PHPExcel 进行任何更改。你只需要在扩展类上使用你的新类。

namespace MyPHPExcel;

class MyDataValueBinder extends \PHPExcel_Cell_DefaultValueBinder 
{
    public static function dataTypeForValue($pValue = null)
    {
      ...method body
    }
}

$returnValue = \MYPHPExcel\MyDataValueBinder::dataTypeForValue( $someValue );
于 2012-09-17T13:10:51.403 回答