如何用 PHP 制作计算器
问题:
创建一个 PHP 计算器,可以计算输入的简单代数表达式由用户使用标准代数符号,包括表达式
常见方法:
一个低效但临时的解决方案涉及替换表达式的字符串表示形式中的表达式,例如:
for ($a=1; $a <p><strong>调车场算法:</strong></p><p>A更有效的方法是使用 Shunting Yard 算法。</p><p><strong>实现:</strong></p><p><strong>终端表达式(值和运算符):</strong></p><pre class="brush:php;toolbar:false">abstract class TerminalExpression { protected $value = ''; public static function factory($value) { // Create terminal expressions based on the provided value (number, operator, or parenthesis) } abstract public function operate(Stack $stack); } class Number extends TerminalExpression { public function operate(Stack $stack) { return $this->value; } } class Operator extends TerminalExpression { protected $precidence = 0; protected $leftAssoc = true; public function getPrecidence() { return $this->precidence; } public function isLeftAssoc() { return $this->leftAssoc; } } class Addition extends Operator { protected $precidence = 4; } class Subtraction extends Operator { protected $precidence = 4; } class Multiplication extends Operator { protected $precidence = 5; } class Division extends Operator { protected $precidence = 5; } class Parenthesis extends TerminalExpression { protected $precidence = 7; public function isParenthesis() { return true; } }
堆栈实现:
class Stack { protected $data = []; public function push($element) { array_push($this->data, $element); } public function pop() { return array_pop($this->data); } }
数学类(执行器):
class Math { protected $variables = []; public function evaluate($string) { $stack = $this->parse($string); return $this->run($stack); } public function parse($string) { // Tokenize expression $tokens = array_map('trim', preg_split('((\d+|\+|-|\(|\)|\*|/)|\s+)', $string, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE)); // Parse operators and parentheses using the Shunting Yard algorithm $output = new Stack(); $operators = new Stack(); foreach ($tokens as $token) { $expression = TerminalExpression::factory($token); if ($expression->isOperator()) { $this->parseOperator($expression, $output, $operators); } elseif ($expression->isParenthesis()) { $this->parseParenthesis($expression, $output, $operators); } else { $output->push($expression); } } // Pop remaining operators on stack and push to output while (($op = $operators->pop()) && $op->isOperator()) { if ($op->isParenthesis()) { throw new RuntimeException('Mismatched Parenthesis'); } $output->push($op); } return $output; } public function run(Stack $stack) { // Evaluate stack and return result while (($operator = $stack->pop()) && $operator->isOperator()) { $value = $operator->operate($stack); $stack->push(TerminalExpression::factory($value)); } return $operator ? $operator->render() : $this->render($stack); } protected function extractVariables($token) { if ($token[0] == '$') { $key = substr($token, 1); return isset($this->variables[$key]) ? $this->variables[$key] : 0; } return $token; } // ... }
使用此实现,您可以按如下方式计算表达式:
$math = new Math(); $answer = $math->evaluate('(2 + 3) * 4'); // 20 $answer = $math->evaluate('1 + 2 * ((3 + 4) * 5 + 6)'); // 83 $answer = $math->evaluate('(1 + 2) * (3 + 4) * (5 + 6)'); // 231 $math->registerVariable('a', 4); $answer = $math->evaluate('($a + 3) * 4'); // 28
以上是如何使用 Shunting-Yard 算法构建 PHP 计算器?的详细内容。更多信息请关注PHP中文网其他相关文章!

在PHP中,可以使用session_status()或session_id()来检查会话是否已启动。1)使用session_status()函数,如果返回PHP_SESSION_ACTIVE,则会话已启动。2)使用session_id()函数,如果返回非空字符串,则会话已启动。这两种方法都能有效地检查会话状态,选择使用哪种方法取决于PHP版本和个人偏好。

sessionsarevitalinwebapplications,尤其是在commercePlatform之前。

在PHP中管理并发会话访问可以通过以下方法:1.使用数据库存储会话数据,2.采用Redis或Memcached,3.实施会话锁定策略。这些方法有助于确保数据一致性和提高并发性能。

PHPsessionshaveseverallimitations:1)Storageconstraintscanleadtoperformanceissues;2)Securityvulnerabilitieslikesessionfixationattacksexist;3)Scalabilityischallengingduetoserver-specificstorage;4)Sessionexpirationmanagementcanbeproblematic;5)Datapersis

负载均衡会影响会话管理,但可以通过会话复制、会话粘性和集中式会话存储解决。1.会话复制在服务器间复制会话数据。2.会话粘性将用户请求定向到同一服务器。3.集中式会话存储使用独立服务器如Redis存储会话数据,确保数据共享。

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

PHP会话的替代方案包括Cookies、Token-basedAuthentication、Database-basedSessions和Redis/Memcached。1.Cookies通过在客户端存储数据来管理会话,简单但安全性低。2.Token-basedAuthentication使用令牌验证用户,安全性高但需额外逻辑。3.Database-basedSessions将数据存储在数据库中,扩展性好但可能影响性能。4.Redis/Memcached使用分布式缓存提高性能和扩展性,但需额外配

Sessionhijacking是指攻击者通过获取用户的sessionID来冒充用户。防范方法包括:1)使用HTTPS加密通信;2)验证sessionID的来源;3)使用安全的sessionID生成算法;4)定期更新sessionID。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

禅工作室 13.0.1
功能强大的PHP集成开发环境

SublimeText3 英文版
推荐:为Win版本,支持代码提示!