If Ruby gets invited to a party and brings:
foobarobject.send('foomethod')
.. and Python gets invited to the same party and brings:
getattr(foobarobject, 'foomethod')()
.. what does PHP have to bring to the party?
Bonus question: If Ruby and Python got jealous of PHP's party-favors, what English terms would they search for in PHP's documentation in order to talk about it behind PHP's back?
PHP brings this:
$foobarobject->{"foomethod"}();
... and the coke and chips.
EDIT:
Although the term for the above is variable variables there is nothing specifically talking about doing it to an object in the manual. However, you can achieve the same thing with call_user_func:
call_user_func(array($foobarobject, "foomethod"));
Using variable to hold the method name. Pretty much the same as Paolo's first example, but maybe not so obvious unless you know about it.
$method = "foomethod";
$foobarobject->$method();
You also got the Reflection classes.
$method = new ReflectionMethod('Foobar', 'foomethod');
$method->invoke(null);
Related
I've seen both used in documentation of a PHP library (seemingly interchangeably) and was wondering if there's a method to the madness and a time when each should be used? (Or if they mean something different, a nuance which I've therefore missed in the documentation)
Examples:
ClassName#foo() // a method
ClassName::bar() // a method
ClassName::baz // a property
I've not (yet) seen anybody try to use ClassName#qux for a property but perhaps that's possible too!
Hopefully this thread will help to set people on the straight and narrow!
Thanks in advance
P.S. it's hard searching Google for this. "#" = "hash" = "pound" and "::" = "double colon" = "T_PAAMAYIM_NEKUDOTAYIM"... and "hash" means something all of its own too, of course.
Edit: A further question is whether it is normal/correct to document properties and variables as ClassName::foo or ClassName::$foo (i.e. with or without a leading $)
Even for PHP, it's perverse, which is saying a lot. Don't ever do it in any context.
It is probably to disambiguate between actual static methods which can literally be called with Foo::bar(), and instance methods which require an object instance, like $foo->bar(). That's the only sensible explanation I can think of, and it's not an official standard in any context that I'm aware of.
How is type ignorance implemented in PHP? For example, I can write the function:
function min($n, $m){
if ($n<$m) return $n;
return $m;
}
Then, I could use that function indifferently with integer, real or even string. I believe this is possible because PHP passes pointers instead of real variables (or reference to variables). Am I right? Can someone point me out a good lecture about internal implementation of PHP or a good explanation of how thing are made?
I should add that I am much interested into the way PHP interpreter make it work. Thank for the answers that were provided until now.
Its because PHP is dynamic. Things are passed by value in PHP. Its called duck typing.
http://en.wikipedia.org/wiki/Duck_typing#In_PHP
By default, PHP passes variables by value, not by reference. It is possible to pass by reference by changing function min($n,$m) to function min(&$n, &$m). For more on pass-by-reference, check out this link on the PHP manual
This also may be helpful for you: http://php.net/manual/en/language.variables.scope.php
Please consider the following code snippet:
From php-5.3.1/ext/session/session.c:
PHPAPI char *php_session_create_id(PS_CREATE_SID_ARGS)
…
gettimeofday(&tv, NULL);
…
/* maximum 15+19+19+10 bytes */
spprintf(&buf, 0, "%.15s%ld%ld%0.8F", remote_addr ?
remote_addr : "", tv.tv_sec, (long int)tv.tv_usec,
php_combined_lcg(TSRMLS_C) * 10);
…
return buf;
}
I have found it on the internet. But I can't understand what code is this. I guess this is the implementation of a php function in C++. If yes, then please explain me how php calles c++ function in it?
The shocking truth is that PHP is written in C. You are looking at the source of PHP itself, or need to explain the question further.
It is not a C++ code, it is pure C. The PHP library can call C functions just like any other library implemented in C. The code snippet generates a "unique" session ID consisting of the client address, the current time, and a pseudo-random number from some linear congruential generator.
I am guessing that you ended up to that piece of code via the DEFCON 18: How I Met Your Girlfriend lecture? Great talk btw. :-)
Now about the code snippet, it is C and it is part of PHP's code. This exact function handles the generation of PHP session ids. You have the entire function logic explained in the lecture i mentioned above, in case you didn't see it.
As a side not, PHP does not call C functions, instead you call a PHP library function and so it happens that most of those functions are written in C and exposed through PHP. On the other hand php_session_create_id does not have an equivalent exposed to PHP, since that one is used internally by PHP when you start a session using PHP session api.
Well I want to learn C++ and at the moment I'm only familiar with PHP and Javascript. And I thought a good way to start learning would be to transfer methods in PHP to C++.
So basically I want the code snippets below in C++
The post with the best comments will get a big green tick.
Also, if you know of a good beginners tutorial please leave a comment.
So here are the bits of code I want in C++
First
$array = array('I\'m', 'learning', 'C++');
foreach($array as $word){
echo $word.' ';
}
Second
function foo($num,$ber, $add = true){
if(is_numeric($num) && is_numeric($ber)){
if(!$add){
echo $num*$ber;
}
else{
echo $num + $ber;
}
}
else{
echo 'They aren\'t numbers!';
}
}
foo(2,4, false);
I'm skeptical about the pedagogical usefulness of translating this into C++. Just translating the above code may not be too useful. Take your first example, where you loop over an array of strings and print out each word - sure, I could translate this into C++ using an std::vector<std::string>, iterate over the vector and output each string to stdout. But is that really going to teach you anything? I could also use a C array of const char* pointers, iterate over that and call printf on each one. But is that really going to teach you anything?
Since you already know how to code in PHP and Javascript, you're obviously aware of basic programming concepts like variables, loops, conditionals, etc. But C++ is a dramatically different language than either PHP or Javascript. For one thing, it's statically typed. For another thing, it requires manual memory management. So I think rather than trying to translate PHP code to C++, you'd be better off reading a good introductory book to C++.
never try to learn any complex subject by 'translating' from another one, no matter how well you know the old one.
You'd only get inconsistent concepts, with the limitations of both and the advantages of none.
I think you'd be much better off if you tried to figure it out and asked questions you had about it along the way.
Why is it not possible to do something equivalent to this in PHP:
(Array(0))[0];
This is just for sake of argument, but it seems strange it does not allow access of anonymous objects. I would have to do something like the following:
$array = Array(0);
$array[0];
Any ideas why this is the behavior of PHP?
I read something somewhat detailed about this once and I regret not bookmarking it because it was quite insightful. However, it's something along the lines of
"Because the array does not exist in memory until the current statement (line) executes in full (a semicolon is reached)"
So, basically, you're only defining the array - it's not actually created and readable/accessible until the next line.
I hope this somewhat accurately sums up what I only vaguely remember reading many months ago.
This language feature hasn’t been inplemented yet but will come in PHP 6.
I guess the short answer is: nobody has coded it yet. I've used (and loved) that syntax in both Python and Javascript, but still we wait for PHP.
The main reason is because unlike some languages like Python and JavaScript, Array() (or in fact array()) is not an object, but an language construct which creates an inbuilt data type.
Inbuilt datatypes themselves aren't objects either, and the array() construct doesn't return a reference to the "object" but the actual value itself when can then be assigned to a variable.