尝试创建对象时出现类未找到错误

时间:2015-02-10 15:03:37

标签: php

而不是:

$price = "356";
$shipping = "0";
$total_price = $shipping + $price;

Price: <?php echo number_format((float)$price, 2, '.', ''); ?>
Shipping: <?php echo number_format((float)$shipping, 2, '.', ''); ?>
Total: <?php echo number_format((float)$total_price, 2, '.', ''); ?>

我想使用这样的对象:

$price = "356";
$shipping = "0";
$total_price = $shipping + $price;

$oformat = new number_format(2, '.', '');

Price: <?= $oformat->format( (float) $price ); ?>
Shipping: <?= $oformat->format( (float) $shipping ); ?>
Total: <?= $oformat->format( (float) $total_price ); ?>

但我得到了:

Fatal error: Class 'number_format' not found in line...

为什么以及如何正确地做到这一点?

2 个答案:

答案 0 :(得分:0)

您要使用的课程称为NumberFormatter。这是一个例子:

<?php 
$price = 356.12;
$shipping = 12.24;
$total_price = $shipping + $price;
$oformat = new NumberFormatter('en_EN', NumberFormatter::DECIMAL);
?>
Price: <?= $oformat->format( $price ); ?>
<br/>
Shipping: <?= $oformat->format( $shipping ); ?>
<br/>
Total: <?= $oformat->format( $total_price); ?>

如果您没有可用的NumberFormatter,您可以创建自己的类:

<?php
class MyNumberFormatter
{
    public function format($valueToFormat)
    {
        return number_format( $valueToFormat , 2, '.', '');
    }
}
$price = 356.12;
$shipping = 12.24;
$total_price = $shipping + $price;
$oformat = new MyNumberFormatter();
?>
Price: <?= $oformat->format( $price ); ?>
<br/>
Shipping: <?= $oformat->format( $shipping ); ?>
<br/>
Total: <?= $oformat->format( $total_price); ?>

答案 1 :(得分:0)

按照以下步骤操作:

  1. 转到&#34; www&#34; wamp文件夹里面的文件夹。
  2. 创建一个文本文件并将其命名为&#34; format.php&#34;。
  3. 复制粘贴下一个代码:
  4. <?php
    class format {
    public function number_format ( $num , $dec, $sep ) {
    // ADD YOUR CODE HERE.
    return $num;
    }
    }
    ?>
    
    1. 创建另一个文本文件并将其命名为&#34; main.php&#34;。
    2. 复制粘贴下一个代码:
    3. < ? php
      require_once( "format.php" ); // IMPORT CLASS.
      $fmt = new format(); // CREATE OBJECT OF YOUR CLASS.
      
      $price = 356;
      $shipping = 0;
      $total_price = $shipping + $price;
      ?>
      Price : <?php echo $fmt->number_format( $price,2,"." ); ?>
      <br/>
      Shipping : <?php echo $fmt->number_format( $shipping,2,"." ); ?>
      <br/>
      Total price : <?php echo $fmt->number_format( $total_price,2,"." ); ?>
      
      1. 启动wamp服务器(屏幕右下方的绿色图标)。

      2. 打开任何浏览器并在地址栏中输入下一行:

        http://localhost:8099/main.php

      3. 说明:在一个单独的文件中创建一个类(&#34; format.php&#34;),然后创建一个类的实例以调用它的方法(&#34; number_format&#34;) 。在单独的文件中更好,因为您可以重复使用该代码。