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 に答える