PHP Arrays, Can I define my own Array class? - php

I can see in PHP 5.3.2 there is an ArrayObject class. Is it possible to declare a new object named Array
that extends the ArrayObject. But Im not sure if 'Array' is a reserved keyword or should I use my own prefix i.e XArray(), MyArray etc...
What I would like to have is
class Array extends ArrayObject {
...my own code
}

All you'd have to do is try to run:
<?php class Array {}
And you'd see:
Parse error: syntax error, unexpected 'Array'
So the answer is, no, you cannot. You'll need to use a different name.

If it works right now, it may just happen that they do create an Array class in the future. It is best just to stay away from names that are so obviously logical for the language to define.
edit: As Matthew pointed out, it doesn't work. Seeing his answer made me realize why it doesn't work: array is a keyword in php (allowing you to make an array literal) and keywords are case insensitive in php.

Im not sure if 'Array' is a reserved keyword
That's pretty easy to check. PHP's list of reserved keywords has "array()" listed front and center.
That page also lists the following guidance:
You cannot use any of the following words as constants, class names, function or method names. Using them as variable names is generally OK, but could lead to confusion.
So no, you can't. You need to rename your class to something else, and your name must be differentiated by more than just letter-casing since PHP class names are case-insensitive.

Related

How to define a class with same name as built-in function?

I would like to define a class named "List" like this:
class List
{
}
PHP gives the following error at the file of the class definition: "Parse error: syntax error, unexpected T_LIST, expecting T_STRING"
Apparently there is a php built-in function named "list()" that the parser is reading here instead of my class definition even though the line starts with the keyword class
Since I don't use the built-in function anywhere in my project I would like to "remove/disable" it, so I can use my class named "List".
Is this possible in php and how?
list is a reserved word as it is a language construct (not actually a function), so no, you cannot disable it. Try being more specific with your class name, e.g., ObjectList or AbstractList.
The class name can be any valid label which is a not a PHP reserved
word.
List of PHP reserved words says list is one of those words.

call_user_func(array(self, 'method')) - do I have to name the class?

In PHP, call_user_func(array(self, 'method_name')) doesn't work. The self keyword cannot be used in that context. I need to actually include the name of the class call_user_func(array('class_name', 'method_name')).
However, if I'm not in a static function, the $this variable does work in that context. Why the difference?
If you want the name of the current class context, use get_class() (without any parameters) or __CLASS__.
You've already written the difference; self is a keyword, and is not usable as a reference in an array (what kind of type should that be in PHP?). get_class() returns a string, and the array()-callback supports using a string as the first name to do a static call.
You can try with __CLASS__ to get the class name. Also it may work to use call_user_func('self::method_name') directly, but I didn't test it and the documentation about callbacks doesn't say anything about this.
self is just an undefined constant, so it expresses 'self'. So these two are the same:
array(self, 'method_name');
array('self', 'method_name');
And depending on the PHP version you use, this actually works, see Demo.
In case it does not work with your PHP version, some alternatives are:
call_user_func(array(__CLASS__, 'method_name'));
or
call_user_func(__CLASS__.'::method_name'));
or (in case you don't need call_user_func):
self::method_name();
Since PHP 5.5, you can do [self::class, 'methodName'].
::class is really useful for situations where you have a class name (maybe a local alias) and you need to generate the full class name as a string.
In PHP 5.3, you can write call_user_func('self::method') or call_user_func(array('self', 'method')). I suppose the latter could work in older versions as well.

php static magic variable set function

I have some code I'm working with that was written by the guy before me and I'm trying to look it over and get a feel for the system and how it all works. I am also fairly new to PHP, so I have a few questions for those willing and able to provide.
The basic breakdown of the code in question is this:
$__CMS_CONN__ = new PDO(DB_DSN, DB_USER, DB_PASS);
Record::connection($__CMS_CONN__);
First question, I know the double underscore makes it magic, but I haven't been able to find anywhere exactly what properties that extends to it, beyond that it behaves like a constant, kind of. So what does that mean?
class Record
{
public static $__CONN__ = false;
final public static function connection($connection)
{
self::$__CONN__ = $connection;
}
}
Second, these two pieces go together. They are each in separate files. From what I've read, static variables can be referenced in the same way as static functions, so couldn't you just call the variable and set it directly instead of using the function?
I get the feeling it's more involved than I am aware, but I need to start somewhere.
This isn't a magic variable. The person who wrote that shouldn't really use double underscores for variable names like that because it can cause confusion.
This is just a static property on a class. Which means it is shared between instances of that class (in the same php request).
Have a look at the docs for static properties if you're unsure on how these work.
There are several predefined "magic constants" that use this naming style. However, I don't think the underscores mean anything special (as far as the language is concerned); i.e. defining your own variable like this won't bestow it any magical properties. It may be part of the previous programmer's naming convention, and if so, it's probably ill-advised.
Setting a property via a function can, in many circumstances, make the "client" code more resilient to changes in the implementation of the class. All implementation details can be hidden inside the method (known as a "setter"). However, there are strong feelings about whether this is a good idea or not (I, for one, am not a big fan).
Two underscores do not make a variable magic.
It's better to use getters/setters than to access class properties directly.
The PHP manual has this to say on naming variables (and other symbols) with underscores:
PHP reserves all symbols starting with __ as magical. It is recommended that you do not create symbols starting with __ in PHP unless you want to use documented magical functionality.
Pay particular attention to the use of the words "reserves" and "documented". They mean double underscores shouldn't be used for user-defined symbols as it may lead to future conflicts, and that unless the symbol is explicitly mentioned in the manual as being magic, it's mundane.

Is it possible to name a constant a protected word in PHP?

In C#, variables and other things can be named protected names such as "class" by prepending the name with an # sign. So, #class is a valid name. Is it possible to do this same thing in PHP? I am using a class of constants to simulate an enum for HTML attributes such as ID, and Class. For now I am using "CssClass" but I'd rather use the name Class somehow.
Nope, not possible, at least not for class constants.
You cannot use any of the following [reserved] words as constants, class names, function or method names.
I don't know about C#, but there isn't any special symbol in PHP to transform a keyword into an identifier. As long as you don't name it exactly the same as a keyword (barring letter case), it'll just be any normal constant name.
How about a (different since it's not just CSS) prefix? Gets repetitive to type, but is a nice workaround. I realize this may be redundant as well if your class is named something like HTMLAttribute, but it's the easiest way out.
const A_ID = 'id';
const A_CLASS = 'class';
// etc
Yes, it is possible.
In fact you can define anything as constant:
define("define", 1);
define("class", 1);
define("if", 1);
define("=.+*", 1);
However, you can not use all defined constants.
You can query them with constant("if") again. But this is not exactly what you asked for. So unlike C# there is no shortcut to use any random constant. But as for naming them, there are almost no restrictions. (Might be a bug though. It's PHP.)
Constants:
The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thusly: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
List of reserved keywords:
These words have special meaning in PHP. Some of them represent things which look like functions, some look like constants, and so on--but they're not, really: they are language constructs. You cannot use any of the following words as constants, class names, function or method name.
[see list here]
Within these rules you're free to make up your names. So, for instance, you could name a constant _CLASS, but not CLASS. I'd avoid the use of such ambiguous names though and namespace constants that are particular to the app, like MYAPP_CLASS.
Going from PHP5 to PHP7, a class constant could be named almost anything:
class ReservedWord
{
// Works in PHP >= 7.0 only
const NULL = null;
const TRUE = true;
}
However, thanks to this part of the manual and this comment, I've found that a class constant cannot be named these few things (see the test here):
class
static
__halt_compiler (oh, that was so useful!)
Edit: As I found in here in an RFC, the reason why class constant does not work is the name resolution ::class. However, still no idea about the two others.

Alternative syntax for accessing a class variable in PHP

I just stumbled upon an interesting syntax in a PHP script:
echo $foo->{'bar'};
$foo in this case is an object returned from PHP's json_decode() function, but it works well when accessing public members of any object.
I've tried to find out why this syntax was used instead of the more common:
echo $foo->bar;
Does accessing a class member with the syntax from the first example offer anything special, compared to the second example?
The curly bracket syntax is useful when you want to reference a function name as a string:
print $foo->{'aMemberFunc'}();
When you want access members which name is provided by another function (or a variable).
Here getVarName() returns a string which can be used to reference a member inside the $foo object.
print $foo->{getVarName()};
Without the curly brackets it would be $foo->getVarName() and it would try and run that method... with the curly brackets it takes a completely different meaning.
echo $foo->{'bar'}; and echo $foo->bar; are identical as far as I can tell.
first syntax allows you to access properties with '-', often used in JSON.
The benefit is that you can have variables names that don't adhere to the rules for naming member variables.
This might seem like a bad idea and usually it is but there are uses for it. An example would be if you were writing an application that allowed its users to add arbitrary fields with human readable names but still be accessible for plugins etc.

Categories