Jump to content

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


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.
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.