at 2006-10-22
in Further reading
by friebe
(0 comments)
Having blogged about Python's new with statement (see entry #117), I decided I'll also mention C#'s using() which is quite similar.
From the C# Reference:
Defines a scope, outside of which an object or objects will be disposed.
Example: using (TextWriter w= File.CreateText("log.txt")) { w.WriteLine("This is line one"); } The above code is a shorthand for: TextWriter w = File.CreateText("log.txt"); try { w.WriteLine("This is line one"); } finally { if (w != null) { ((IDisposable)w).Dispose(); } }...and is actually translated by the C# compiler to the latter (see also Understanding the 'using' statement in C#).
Possibilites Now think about the possibilities this gives us when creating our own implementations of the Dispose() method. Here's one: using (Transaction t= connection.BeginTransaction()) { // ... performs inserts, updates, deletes... t.commit(); }(see also Easier Database Transactions - Extending the Using Statement...).
Would this make sense in PHP? For core PHP, using() would only have limited use, as most functions such as fopen() or mysql_connect() won't actually throw exceptions but rather return FALSE (or NULL, or -1, it's not that they're really consistent with this ).
For the new object-oriented extensions such as PDO, or of course within the XP framework, this would be a great addition though.
Idea:
<?php $conn= DriverManger::getConnection($dsn); using ($conn->begin(new Transaction('update_person')) as $t) { $conn->query('update person ...'); $conn->query('insert into synchronization ...'); $t->commit(); } ?> If you're wondering why there's no RFC on this: Implementing this in PHP userland is not possible without having to pass the entire sourcecode within the using block as a string, which seems quite ugly (see this experiment).
If there were to be using() for PHP, it should really go into the PHP core. Or, of course, into a preprocessor / translator of some sort - but that's a different story
|
Subscribe
You can subscribe to the XP framework's news by using RSS syndication.
CategoriesNews General PHP5 Announcements RFCs Further reading Examples Editorial EASC Experiments Unittests Databases
RelatedFind related articles by a search for «C#'s».
|