I am looking at this tutorial:
http://www.joelverhagen.com/blog/2011/05/setting-up-codeigniter-2-with-doctrine-2-the-right-way/
and I see the new keyword used like so:
$doctrineClassLoader = new \Doctrine\Common\ClassLoader('Doctrine', APPPATH.'libraries');
I am not used to seeing the new keyword used with what appears to be a directory or something? I was looking through the PHP manual to find similar usage and what this means (and how it works) but didn't see what I was looking for.
Can someone explain this usage to me or point me to example code in the PHP manual.
PHP 5.3 introduced namespaces. Namespace are another way of structuring your program and the library you are working with is using them extensively. You can basically put classes and functions inside a namespace. Namespaces can be nested. In order to use them you prefix every namespace by a backslash.
You can read more about namespaces in the PHP manual.
Related
I have been reading about Using namespaces: Aliasing/Importing in PHP. There are two things I don't understand.
It says,
Note that for namespaced names (fully qualified namespace names
containing namespace separator, such as Foo\Bar as opposed to global
names that do not, such as FooBar), the leading backslash is
unnecessary and not recommended, as import names must be fully
qualified, and are not processed relative to the current namespace.
Can someone please explain
What does it mean?
What's the purpose of using namespaces aliasing ? Given that I know the purpose of using namespaces.
What does it mean?
It really means what it says and shows in the example. When importing a namespaced class, you should omit the first backslash:
use My\Full\Classname as Another; // recommended
use \My\Full\Classname as Another; // not recommended
The reason being that use expects a fully qualified namespace. You cannot use a relative path. In other words if you are in the My\ namespace already, you cannot use Full\Classname.
What's the purpose?
It's explained in the first chapter actually:
In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions:
Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem, improving readability of source code.
So, the purpose is to shorten and/or to avoid clashes, e.g. when you have two classes called Foo and need to use both, you have to have a way to resolve that conflict (at least if you don't want to use the fully qualified name each time):
use My\Very\Long\Namespaced\Class\Named\Foo as Foo;
use My\Other\Foo as OtherFoo;
And then you can use
$foo = new Foo;
$otherFoo = new OtherFoo;
So that's short and simple and doesn't clash. There really isn't much more to it.
You might need to import two totally separate name spaces, that happen to have the same name. Like, maybe you need to select data from mysql and then insert into oracle, and you're using some database library which uses namespacing.
use Database\Mysql\Connection;
use Database\Oracle\Connection;
$conn = new Connection(); //which one is it??
You could either skip importing a namespace
use Database\Mysql\Connection;
use Database\Oracle\Connection;
$conn = new Database\Mysql\Connection();
or alias at least one of them
use Database\Mysql\Connection as MysqlConnection;
use Database\Oracle\Connection as OracleConnection;
$conn = new MysqlConnection();
Is there any project like PHP.js but in vice direction to provide PHP implementation of JS classes and functions? In particular Date, RegEx, String classes?
I found this class for String but I am looking for a more complete collection.
My consern is not about using or not using such thing, I just need such thing.
Today I found jsphp. It seems promising.
JavaScript for PHP (jsphp) is a pseudo-implementation of the ECMA 262
standard (JavaScript 8.5.1) for PHP 5.3+. It allows you to write code
in PHP as if it were JavaScript, using the standard API and the
dynamic attributes available in the language, such as prototype
inheritence and chaining, first-class functions, and other
object-orientated features. It includes JSBoolean, JSNumber, JSString,
JSObject, JSArray, JSFunction, JSRegExp, JSDate, JSError and JSMath,
as well as the global helper functions, such as parseInt or isNaN.
The syntax in jsphp is very similar to a native implementation, although adapted to the syntax of PHP. For example, the variables are
prepended by a "$", the Object access opertaor is "->", and Strings
are concatenated using a ".".
$myString = new JSString( 'Hello World' );
$myString = $myString->split( '' )->reverse()->join( '' );
print( 'Reversed: ' . $myString ); // dlroW olleH
There is not - and there can not be - somehting like you ask for.
Javascript has a special syntax for regular expressions, something PHP could not take.
Similar how "object" methods in javascript are invoked. And the scope of variables is different. So this would not work.
Instead use the PHP functions. If they are not complete or useable enough for you, wrap them into objects so you can create an interface you like. Or use one of the many libraries that are available.
I just saw the use of a backslash in a reference to a PHP object and was curious about it (I have never seen this before). What does it mean?
$mail = new SendGrid\Mail();
If you're curious, here's SendGrid's documentation.
It's because they're using PHP namespaces. Namespaces are new as of PHP 5.3.
It's PHP's namespace operator: http://php.net/manual/en/language.namespaces.php.
Don't ask why it's a backslash. It's (imho) the stupidest possible choice they could have made, basing their decisions on a highly slanted/bigoted scoring system that made sense only to the devs.
This is syntax for namespaces. You can read more about namespaces at PHP documentation. They they require at least PHP 5.3.
For example:
namespace SendGrid;
function Mail() {
// You can access this function by using SendGrid\Mail() externally
}
This is similar to Can PHP instantiate an object from the name of the class as a string?.
I'm using propel orm with PHP 5.2.17, and I want to store the name of a query class in the database, say "AuthorQuery", then use it to get a query object. There may be a different way to do this with propel, avoding the ::create() factory method. That solution would be welcome, but I'd rather to know if this is even possible with php (I won't be terribly surprised if the answer is "It's not").
Here's the problem. This will work:
$author_class = "Author";
$author = new $author_class();
Using the new keyword a string will get interpreted as the class name.
But I get syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM (that's referring to the ::) when I try to do it using a factory constructor instead:
$author_query_class = "AuthorQuery";
$author_query = $author_query_class::create(); // syntax error at the ::
Do I need an extra $ or something?
It turns out, this is not an issue for PHP 5.3+
Works exactly the way you describe (as far as I remember) with PHP5.3. However, if you still use 5.2, you can use reflection
$x = new ReflectionClass($author_query_class);
$author_query = $x->getMethod('create')->invoke(null);
Or just
$author_query = call_user_func(array($author_query_class, 'create'));
Worth to mention, that this is "much magic" and it will get hard to understand, what happens, when you have many of such constructions.
$author_query=call_user_func("$author_query_class::create");
This has to do with this line:
$author_query_class::create();
It is because (as quoted from the book PHP Master):
The double colon operator that we use for accessing static properties
or methods in PHP is technically called the scope resolution operator.
If there’s a problem with some code containing ::, you will often see
an error message containing T_PAAMAYIM_NEKUDOTAYIM. This simply refers
to the ::, although it looks quite alarming at first! “Paamayim
Nekudotayim” means “two dots, twice” in Hebrew.
You can do something like this in PHP 5.3 and more support is is on the table for PHP 5.4. Before PHP 5.2 you may have to use something like the other answers provided or , gulp, eval().
when I was looking for some MVC framework, I got the website:
http://www.phppatterns.com/docs/design/archive/model_view_controller_pattern
however, like the code listed there makes me confused about references.
For example:
$dao=& new DataAccess ('localhost','user','pass','dbname');
$productModel=& new ProductModel($dao);
each instance it makes, it adds '&' before the new operator, what does it exactly mean? the reference to the instance? Actually, I removed all the '&' before all these kind of instances and the code still works perfectly.
Another, codes like :
function ProductView (&$model) {
$this->model=& $model;
}
I really think it could be revised like:
function ProductView (&$model) {
$this->model=$model;
}
Am I right? what's the differences between these two? Actually, like the MVC code example listed above? if you revise the code like I did, the code still works.
Then, I got this post somewhere else:
http://schlueters.de/blog/archives/125-Do-not-use-PHP-references.html
does it make sense? any suggestions about this would be helpful.
Prior to PHP version 5 objects were passed by value and you had to explicitly specify the ampersand to get the object by reference.*
In PHP 5+, all objects are passed by reference and thus using ampersand is redundant.
Furthermore, as of PHP 5.3.0, code like the above will generate a STRICT error of "Assigning the return value of new by reference is deprecated".
If you're curious about the historical use (PHP 4 or before) of "$o =& new Object()" code see php-by-reference (in particular, the accepted answer there provides a good explanation).
To summarise:
in PHP 5 or above, it makes no difference. The code will work as expected with no memory or other differences.
In PHP 5.3 you might get some STRICT notices complaining about this usage (assuming you have STRICT notices turned on).
In PHP 4.x (or earlier) this method was used to prevent unnecessary duplication of objects.
(*) Passing references around is a good thing - no need to create copies of objects when you only need the one instance.