What was the last thing you learned by accident?

When you think of the "PHP community", what comes to mind first?

The same 50 developers on Twitter who keep arguing?

The people you meet and interact with at conferences and meetups?

Reddit's r/php?

Forums and discussion sites like StackOverflow or SitePoint's forum?

Maybe even the folks who send you PRs to your projects, but whom you've never met in real life?

All those are part of the community, and all are beneficial. Dismissing even one of those sources and underestimating the power of the community is a mistake, because you never know when one of these silos will yield useful information.

One such instance happened fairly recently, when I saw this tweet in my stream:

TIL @var docblocks also work on grouped declarations for completion pic.twitter.com/jv7gb0eBN2

— Sebastian【ツ】 ( @sebdedeyne ) September 20, 2016

TIL indeed!

Whenever we've been typing out type hinted properties one line by one line like so, in order to get our IDE to autocomplete things for us:

/* @var int */
private $something;

/* @var int */
private $somethingElse;

... we could have instead been using a single-line method like this:

/* @var int */
private $something, $somethingElse;

Talk about reducing amounts of code! Think about all those long classes with huge lists of properties that could easily shave off 50 or so lines of code with this approach!

Granted, this is a bit IDE-specific since there's no actual standard for docblocks. After all, what one IDE does, another might be ignoring completely, but it's still good to know. What's more, after discussing this with some people, several of them realized they never knew you could actually declare multiple properties on the same line at all!

So this was my recent #TIL tidbit that I happened upon by accident. What was yours? Did you have a small but significant revelation in a similar way?

True, but my preference I find it easier to have it easier having the variables / properties on a separate line. It makes it easier to read and debut in my opinion. Granted in the early days of programming saving code was essential especially for critical tasks (Apollo 11 moon landing for example :slight_smile: ). However, with computers being fast and storage space being vast there really isn't much of a need to save that much space (code). Just my .02 cents.

1 Like

depends on the task. if variables are only defined, i would use a one-liner, up to five vars or so. if i have to make presets, especially with arrays, i would prefer to use multiline definitions.

To my shame, I learn something surprising mostly when I am bullying someone for not reading the manual... eventually finding that it was me who actually didn't read o.O

For example, recently I learned that mysqli::affected_rows returns the number of rows found for SELECT statements (acting like mysqli_num_rows()).

Another case was with PDO constructor, which throws an exception on error unconditionally, being unaffected by the PDO::ATTR_ERRMODE configuration setting. Had to check the PHP source code and find that it is so.

1 Like

although this is mentioned in the docs:

Errors/Exceptions

PDO::__construct() throws a PDOException if the attempt to connect to the requested database fails.

Yup, but I had the opposite experience (which turned to be a false memory probably) so I decided to double-check.

Interesting because some two years ago I came up with a similar idea with .htaccess and I used it for thumbnail images - if an image file does not exist then run a php script that generates and outputs one, otherwise load the file directly skipping the whole php stack and it seems to be very efficient. Nice to see frameworks implement this kind of stuff :slight_smile: However, this creates a dependence on Apache so something to keep in mind.

Most often I learn new stuff by accident when reading other people's code and tutorials, for example I learned a few things about using PDO from @colshrapnel's guide. There are some minor stylistic things I adopted from other people's code, for example splitting the shorthand conditional syntax into separate lines for readability, especially when the segments are long:

$value = $obj->isValid() && $obj2->hasItems()
  ? ("contains " . $count . " items")
  : "no items found";

Splitting object chaining into lines, inspired by SwiftMailer's documentation:

$obj->doSomeStuff($arg)
  ->doMoreStuff($arg2);

It is a good thing to read tutorials, articles and discussions about programming from time to time apart from practical coding for work because it allows us to discover new possibilities and styles. For example, I used to indent similar items with spaces for visual clarity:

$arr['a']        = 'a';
$arr['abc']      = 'b';
$arr['abcdefgh'] = 'c';
$arr['ab']       = 'd';
$arr['']         = 'e';

I thought it was cool and useful but after reading some opinions I saw a few drawbacks with this style so I stopped using it.

2 Likes

I am usually putting the semicolon on a separate line

$obj->doSomeStuff($arg)
    ->doMoreStuff($arg2)
    ->andMoreStuff($arg3)
;

this is a trick similar to adding a comma to the last array item:

$array = [
    1 => 'foo',
    2 => 'bar',
];
  • it lets you easily add new lines or comment out existing ones. And it doesn't spoil the diff in CVS when you add a new line. Makes the diff more tidy and actual :slight_smile:
2 Likes

'What was the last thing you learned by accident?'

Always and i mean Always check the electric is off when re-wiring a light!

30ma still gives you a jolt! :wink:

2 Likes

... and always check that the main RCCB switch is still on when you set electricity on the newly wired light.

I recently learned that PDOStatement implements Traversable to provide the result set to a foreach:

$stmt = $pdo->query("SELECT * FROM [...]");

// Then in template code:

foreach ($stmt as $row) {
    echo $row['column'];
}

I've been using PDO for years and always used one of the fetch methods for accessing result data:

$stmt = $pdo->query("SELECT * FROM [...]");

while ($row = $stmt->fetch()) {
    $results[] = $row;
}

// OR

$results = $stmt->fetchAll();

// Then in template code:

foreach ($results as $row) {
    echo $row['column'];
}

I discovered this on accident when I was helping my younger brother perform his university work and saw how his text instructed him to access results that way.

1 Like

Just Stumbled upon an absolute gem that will make using this forums so much easier :slight_smile:

When reading a post with HTML just copy and paste the script into one of the following:

HTML Online Editors:

http://editor.cloxy.net/
http://rendera.herokuapp.com/
http://www.onlinehtmleditor.net/
http://scratchpad.io/aspiring-copper-1914
http://www.htmlinstant.com/
http://htmledit.squarefree.com/

Now no need to copy, paste and save the script to my local computer then open with a browser - wonderful!

I was also amazed to learn that the copied script was able to saved using scratchpad.io. I don't know how long the page is saved?

Best of all they are all FREE.

Caught me by surprise while writing unit tests: any namespace alias you define in a trait is included in the class that uses this trait and hence emits an error if you define that namespace alias in the class file (e.g. because you need that class in the code as well).

Two other issues just came to my mind, hope you don't mind

  • starting from 5.4, mysqli_result class implements Traversable interface and thus you can foreach over it directly, just like a statement in PDO. The way I learned it is described in my other answer.
  • the greatest thing about mysqli I've learned so far is that it is able to throw exceptions on SQL errors. I was puzzled though, how to make it work without throwing warnings from mysql server as well, for most of them are rather pointless. It took me a lucky accident of finding a PHP bug (which is now deleted) where it was described that configuration options for mysqli_report() form a bit mask. After that I was able to conjure the proper syntax:
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

it looks not that obvious but works perfectly.

I am trying to advertise this amazing feature on Stack Overflow but without much success. It looks like that notorious or die() will die only with PHP itself...

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.