2

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.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
Scott
  • 5,338
  • 5
  • 45
  • 70
  • 5
    throw is a php keyword. Its part of the Exception handling in PHP. You can't add your own keyword. Read more here: http://www.php.net/manual/en/language.exceptions.php – datasage Jul 08 '11 at 19:33
  • Aw, really? Well thank you anyways :) – Scott Jul 08 '11 at 19:33
  • 3
    you could just have a function `add_environment` declared as part of you framework initialisation process... – Endophage Jul 08 '11 at 19:36
  • 3
    it is far easier to just set `$_ENV['varname'] = 'value'` Most php programmers will know how to do that. When designing a system or api, you want it to be as standard as possible. don't add stuff because it seems easier to you, or saves a few keystrokes. This will just confuse your users. – Byron Whitlock Jul 08 '11 at 19:36

3 Answers3

5

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.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
3

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

zneak
  • 134,922
  • 42
  • 253
  • 328
1

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);
Mike
  • 23,542
  • 14
  • 76
  • 87