Simulated Ruby symbols in PHP -
ruby , other languages have convenient feature: symbols. in-place constants. wonder if following approach simulating symbols in php an @ sign before unquoted string valid approach.
$array = [@key => "value"]; echo sprintf("%s php symbols %s\n", @testing, $array[@key]);
i understand there drawbacks against formal constants , like, same ruby's symbols: consider typing errors. there other considerations against using approach?
you suppressing error (a notice, exact). not costs processing time mentioned in cwallenpoole's answer, error there reason. reason is:
notice: use of undefined constant hello - assumed 'hello' in ...
you relying on constant being undefined - notice trying tell you. if constant of name defined, grab value instead.
in ruby, :__line__
quite different __line__
. former symbol - equals no matter use it. latter number, , magical variable changes value on every line. in php, @__line__
same __line__
, because there no error suppress. oh, , there's 1 special "symbol" extra-fun debug: @exit
, aka @die
.
in ruby, can use sorts of symbols including operators , keywords. these (and many more) valid: :+
:*
:<
:<<
:[]
:[]=
:while
:case
:x=
. pair of parentheses, can use symbols :case=
, :while=
. in php, none of these work. you'll end parse error. won't suppressed. exception @[]
in php 5.4, produces empty array. on other hand, lots of php expressions not valid ruby symbols: @(1+1) === @2
@1 == @'1'
ruby's symbols not equal else. purpose of existence. sure, have nice properites to_s
, to_proc
, original purpose serve identifiers separate possible user input. sorta nice example if using symbols represent tokens in lexer stream, such [:lparen, 1, :plus, "rparen", :rparen]
. in php, undefined constants strings. in ruby, ?test != "test"
. in php @test === "test"
(assuming dindn't define constant named "test" equal else).
you can't assume non-magic constants won't change. can't attribute malice can explained bad coding. nothing of worry in ruby:
//in library code: $this->status = @done; // bad //outside library code: define('done', "no"); // bad define(@done, "yes"); // worse echo @no; // prints "yes" //in library code: if($this->status == @done){ //won't execute } echo @die; echo "this won't printed!";
you shouldn't rely on constants being undefined, , shouldn't use error suppressing hide error messages telling that. shouldn't use special notation pretend 2 things not equal when are. also, can trust users of library not redefine constants @ runtime?
Comments
Post a Comment