aboutsummaryrefslogtreecommitdiff
path: root/README.md
diff options
context:
space:
mode:
Diffstat (limited to 'README.md')
-rw-r--r--README.md84
1 files changed, 27 insertions, 57 deletions
diff --git a/README.md b/README.md
index 3ed5a95..c665575 100644
--- a/README.md
+++ b/README.md
@@ -23,9 +23,9 @@ composer require nxp/math-executor
## Sample usage:
```php
-require 'vendor/autoload.php';
+use NXP\MathExecutor;
-$executor = new \NXP\MathExecutor();
+$executor = new MathExecutor();
echo $executor->execute('1 + 2 * (2 - (4+10))^2 + sin(10)');
```
@@ -84,60 +84,21 @@ Default operators: `+ - * / ^`
Add custom operator to executor:
```php
-<?php
-namespace MyNamespace;
-
-use NXP\Classes\Token\AbstractOperator;
-
-class ModulusToken extends AbstractOperator
-{
- /**
- * Regex of this operator
- * @return string
- */
- public static function getRegex()
- {
- return '\%';
- }
-
- /**
- * Priority of this operator
- * @return int
- */
- public function getPriority()
- {
- return 180;
- }
+use NXP\Classes\Operator;
- /**
- * Associaion of this operator (self::LEFT_ASSOC or self::RIGHT_ASSOC)
- * @return string
- */
- public function getAssociation()
+$executor->addOperator(new Operator(
+ '%', // Operator sign
+ false, // Is right associated operator
+ 170, // Operator priority
+ function (&$stack)
{
- return self::LEFT_ASSOC;
+ $op2 = array_pop($stack);
+ $op1 = array_pop($stack);
+ $result = $op1->getValue() % $op2->getValue();
+
+ return $result;
}
-
- /**
- * Execution of this operator
- * @param InterfaceToken[] $stack Stack of tokens
- * @return TokenNumber Result of execution
- */
- public function execute(&$stack)
- {
- $op2 = array_pop($stack);
- $op1 = array_pop($stack);
- $result = $op1->getValue() % $op2->getValue();
-
- return new TokenNumber($result);
- }
-}
-```
-
-And adding to executor:
-
-```php
-$executor->addOperator('MyNamespace\ModulusToken');
+));
```
## Logical operators:
@@ -171,16 +132,25 @@ $executor->setVars([
echo $executor->execute("$var1 + $var2");
```
## Division By Zero Support:
-By default, the result of division by zero is zero and no error is generated. You have the option to throw a `\NXP\Exception\DivisionByZeroException` by calling `setDivisionByZeroException`.
-
+Division by zero throws a `\NXP\Exception\DivisionByZeroException`
```php
-$executor->setDivisionByZeroException();
try {
echo $executor->execute('1/0');
-} catch (\NXP\Exception\DivisionByZeroException $e) {
+} catch (DivisionByZeroException $e) {
echo $e->getMessage();
}
```
+If you want another behavior, you should override division operator:
+
+```php
+$executor->addOperator("/", false, 180, function($a, $b) {
+ if ($b == 0) {
+ return 0;
+ }
+ return $a / $b;
+});
+echo $executor->execute('1/0');
+```
## Unary Minus Operator:
Negative numbers are supported via the unary minus operator. Positive numbers are not explicitly supported as unsigned numbers are assumed positive.