Jump to content

Can this PHP code be valid: $4bears = $bears->getFirst4();


ansharma

Recommended Posts

Yes it's valid. The -> notation specifies that you're using a function, getFirst4(), belonging to a class ($bears is a copy of this class), and that you want to assign the result of that function to your variable $4bears.

is it possible to define a variable name starting with number?

like this $4xyz=5;

 

Yes but only in the form:

 

${4xyz} = 5;

 

You also need to access it in the same way:

 

print ${4xyz};

 

As a side note: You should avoid writing variables like that.

is it possible to define a variable name starting with number?

like this $4xyz=5;

 

It's a valid variable name, in the sense that a variable can exist called "4xyz". However, it is not a valid label (the part that comes after $ to denote a variable). 

 

In other words, you cannot define a variable name like $4xyz but you can define it using the $GLOBALS superglobal variable ($GLOBALS['4xyz']) or a variable-variable ${'4xyz'}.

 

But... don't.

 

 

 

As a side note: You should avoid writing variables like that.

 

Mostly because it will generate a parse error. :)

This question raised my curiosity as to Why can't variable names start with numbers?

 

Apparently because:

 

It's likely a decision that came for a few reasons, when you're parsing the token you only have to look at the first character to determine if it's an identifier or literal and then send it to the correct function for processing. So that's a performance optimization.

 

Use of a digit to begin a variable name makes error checking during compilation or interpertation a lot more complicated.

 

Because if it did, it would be called COBOL.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.