smn/phsystem

PHP 的占位符系统

1.0.0 2020-09-06 23:25 UTC

This package is auto-updated.

Last update: 2024-09-07 08:50:50 UTC


README

一个简单的类,用于替换字符串模式中的值

要求

  • PHP >= 7.4
  • Composer

安装

composer require smn/phsystem

用法

这个简单的类使用一个模式和一组占位符

模式是一个包含占位符的字符串或短语。占位符用“{ }”包围

占位符列表是一个包含键/值对的列表,其中值是一个简单的字符串或一个回调函数

简单值

<?php
$ph = new PlaceHolderSystem();
$ph->setPattern('I have 5 {fruit}');
$ph->addPlaceHolder('fruit', 'apple');
echo $ph->render(); // I have 5 apple

回调函数

<?php
$ph = new PlaceHolderSystem();
$ph->setPattern('i learned how to count to {number}');
$ph->addPlaceHolder('number',function() {
 return 30;
});

echo $ph->render(); // i learned how to count to 30

带有参数的回调函数

<?php

class Num {

  public $val = 5;

}

$instance = new Num();
$ph = new PlaceHolderSystem();
$ph->setPattern('i learned how to count to {number}');
$ph->addPlaceHolder('number', function($param) {
 return $param->val;
}, [$instance]);
// Third parameter of addPlaceHolder method is an array with a list of parameters for callback function.

echo $ph->render(); // i learned how to count to 5

$instance->val = pow(2,16);
echo $ph->render(); // i learned how to count to 65536