Creating a new “command” in PHP

2019-05-18 18:52发布

I've seen some PHP applications use lines of code that are like this:

throw new Exception(....);

How do I make one of those? I want to make sort of 'throw' command. What is that called?

For example, I'm writing an application, and I want to make the backend easy to use, so I want to use this when a developer wants to set an environment variable:

add environment("varname","value");

But I have no idea how to make one of those.

3条回答
ゆ 、 Hurt°
2楼-- · 2019-05-18 19:22

I think you're better just to use some sort of an object to do what you want. Like this:

<?php

class Environment
{
    public $arr = array();
    public function add($name, $value) {
        array_push($this->arr, array($name, $value));
    }
}

$env = new Environment;
$env->add('foo','bar');
print_r($env->arr);
查看更多
Animai°情兽
3楼-- · 2019-05-18 19:37

throw is built into the language. Doing what you want would require either modifying the PHP compiler or implementing a DSL, neither of which are simple tasks.

查看更多
不美不萌又怎样
4楼-- · 2019-05-18 19:42

throw is a keyword defined by PHP. There is no way, without modifying the PHP parser, to do what you're asking for.

查看更多
登录 后发表回答