When to add brackets after new class name? [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP class instantiation. To use or not to use the parenthesis?
Omission of brackets and parameter-less object constructors
With or without the brackets, the new Class seems not bother. So, I doubt what's the usage of the brackets (). I searched php manual, didn't get it. Could anybody explain?

The purpose of the brackets is for you to enter any arguments that your constructor may accept.
class Example{
private $str;
public function __construct($str){
$this->str = $str;
}
public function output(){
echo $this->str;
}
}
$ex = new Example; // missing argument error
$ex = new Example('Something');
$ex->output(); // echos "Something"
If your class constructor does not accept any arguments, you may leave the brackets out. For good code sake, I always keep the brackets, whether or not the constructor accepts any argument.
Most coders coming from C# or Java background would keep the parenthesis as it is more familar to them.

Related

Why is {'property'} used in PHP [duplicate]

This question already has answers here:
How and why use curly braces: return $this->{$this->action}();
(2 answers)
Closed 6 years ago.
Feel free to re-title this Question because I do not know the proper name for doing this. More to the point, I have seen people using {'property'} when accessing a property inside an object so I set-up an example to try understand however, the property is accessible when I use it and when I don't?
class Example {
public $name;
}
$e = new Example();
$e->{'name'} = 'Kdot';
echo $e->name; // output: Kdot
I have tried changing the scopes and accessing it through a class method but it works both ways, again.
Can someone help me understand what the meaning of using the {} delimiters are? Because from my knowledge, if you stored the parameter inside another variable, this would also work:
$property = 'name';
echo $e->$property; // output: Kdot
They're mostly both just different ways to do the same thing, but with slightly different capabilities.
One difference is that if you want to concatenate inline and use that for a property name, you need the braces:
// example:
$property = 'foo';
echo $e->{$property . 'Suffix'}; // good, uses $e->fooSuffix
echo $e->$property . 'Suffix' // bad, uses $e->foo and adds "Suffix" literal
As well as that, directly access property names need to conform to certain rules. For example if you have a dash in your property name you need to use braces to access it.

Static vars - what are they and when should they be used? [duplicate]

This question already has answers here:
Static methods in PHP: what for?
(2 answers)
Closed 8 years ago.
I'm trying to figure out what static vars are.
They can be access without instantiating the class but what other benefits do they have and when should they be used?
For example, my class has a private var which holds the name of the twitter feed i'm trying to get.
Should this be static? It never needs to change.
Generally things which aren't instance specific but needs to be stored in a variable should be static variables. Otherwise this manual tells the details: http://php.net/manual/en/language.variables.scope.php
Otherwise you can consider using constants also. For the example you mentioned (as others wrote) using constants seems to be the most sensible. (Either a class constant, or simple one.)
Static variables are for when you want a variable inside a function to keep it's value if the function is called again.
An example of a static variable could be the following.
function addOne(){
static $i = 0;
$i++;
return $i;
}
echo addOne();
echo addOne();
echo addOne();
Which would return
123
Without the static keyword, this would simply return
111
In your question, you mention you have data that won't need to be changed. As the comments in the question state, you should make this a Constant.
In short, static variables can be used for constants.
For example, a Math class can have static variables; PI etc.
Let's say you have something in a class that you need later.
Now, you need that thing but you don't actually need|want|should create a new instance of that class.
That's why you use a static method/property

What is the use cases for nested function declarations in PHP? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What are PHP nested functions for?
PHP allows nested function declarations like so:
function foo() {
function bar() {
return "bar";
}
return "foo";
}
But what are the use cases for such a syntax? The inner bar is put to
global namespace so so it's not garbage collected, is usable from outside
the outer function and provides a lot of confusion and possible bugs. For
example calling the foo twice results in an error, unless you wrap the
declaration inside a if(!is_callable('bar')).
Using nested declarations to create conditional declarations is not good
either, because of the confusion it creates. "Why is it complaining that
there is no such function, when it works perfectly fine in there?!?!".
Well, conditional function declaration is probably the only legitimate use case, and there only to provide fallbacks for backwards compatibility:
function makeSureAllDependenciesExist() {
if (!function_exists('someFunctionThatOnlyExistsInNewerPhpVersions')) {
function someFunctionThatOnlyExistsInNewerPhpVersions() {
// fallback implementation here
}
}
}
Other than that, there's indeed little reason to use nested function declarations.

finding the name of method i am in [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
get current class and method?
How can i find the name of the method i am using in php? I found how to do this in C but not in PHP. I found a Q on here which roughly talked about magic constants (here) but I didn't really get it. In the following example I want $thisMethodName to be 'model_databaseLogin'
EG:
public function model_databaseLogin()
{
$thisMethodName = ... ;
return $this->model_methodCheck( $thisMethodName );
}
Is this possible in php?
You need the "magic constant" __METHOD__. The magic constant docs should be helpful.
So your code would be:
public function model_databaseLogin() {
$thisMethodName = __METHOD__;
return $this->model_methodCheck($thisMethodName);
}
The simplest answer is the magic constants to which you refer; specifically __FUNCTION__
These are called "magic" because their value is actually contextually dynamic.
public function model_databaseLogin()
{
$thisMethodName = __FUNCTION__;
return $this->model_methodCheck( $thisMethodName );
}
There is another way, via debug_backtrace(), but that is decidedly less efficient!

Can I immediately evaluate an anonymous function? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Immediately executing anonymous functions
I want to immediately evaluate an anonymous function rather than it appearing as a Closure object in method args. Is this possible?
For example:
$obj = MyClass;
$obj->Foo(function(){return "bar";}); // passes a Closure into Foo()
$obj->Foo(function(){return "bar";}()); // passes the string "bar" into Foo()?
The 3rd line is illegal syntax -- is there any way to do this?
Thanks
You could do it with call_user_func ... though that might be a bit silly when you could just assign it to a variable and subsequently invoke the variable.
call_user_func(function(){ echo "bar"; });
You might think that PHP 5.4 with it's dereferencing capabilities would make this possible. You'd be wrong, however (as of RC6, anyway).

Categories