PHPExcel_Cell_DefaultValueBinder::dataTypeForValue()
後でライブラリをアップグレードする際に問題が発生しないように、ライブラリ PHPExcel に触れずにメソッドを上書きしたいと思います。
実際のところ、数値を文字列に変換する問題を解決するためにこれを行っています。後で問題なくライブラリを使用し続けることができるように、メソッドを上書きする方法を知りたかっただけです。
から継承する新しいクラスを作成し、関数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を使用します:)
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);
}
}
クラスを拡張し、機能を拡張したいメソッドをオーバーライドできます。これは、 SOLID プログラミングのオープン/クローズの原則 (拡張はオープン、変更はクローズ) に従っており、PHPExcel に変更を加えていません。拡張クラスで新しいクラスを使用するだけです。
namespace MyPHPExcel;
class MyDataValueBinder extends \PHPExcel_Cell_DefaultValueBinder
{
public static function dataTypeForValue($pValue = null)
{
...method body
}
}
$returnValue = \MYPHPExcel\MyDataValueBinder::dataTypeForValue( $someValue );