Viewed   67 times

Why can't I do this in PHP? Where Database is a singleton class and getInstance() returns a PDO object.

<?php

class AnExample
{
    protected static $db = Database::getInstance();

    public static function doSomeQuery()
    {
        $stmt = static::$db->query("SELECT * FROM blah");
        return $stmt->fetch();
    }
}

Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.

http://php.net/manual/en/language.oop5.static.php

Why?!

 Answers

2

http://php.net/language.oop5.properties

Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

The important part is

that is, it must be able to be evaluated at compile time

Expressions were evaluated at runtime, so it isn't possible to use expression to initialize properties: They are simply not evaluatable yet.

Wednesday, October 5, 2022
3

Static scoping does not mean it will stay in memory forever, it means that the variable operates outside the program call stack, and will persist during the execution of the script. It is still cleared after the program ends.

Friday, September 23, 2022
 
4

Recursive functions are OK - but dangerous if you aren't sure you know what you are doing. If there is any chance that a function will end up in a recursive loop (where it keeps calling itself over and over) you will either time out, run out of memory or cause a zombie apocalypse.

Think of recursive calls as a really, really sharp knife - in the hands of an experienced chef, it's a match made in heaven, in the hands of the dishwasher, it is a lost finger waiting to happen.

PHP tries to play nice, and limits a recursive depth to 100 by default (though this can be changed) but for almost all cases, if your recursive depth gets to 100, the accident has already happened and PHP reacts by stopping any additional pedestrians from wandering into traffic. :)

Tuesday, September 13, 2022
4

did you check this : http://www.java2s.com/Code/Php/Class/InterceptingMethodCallswiththecallMethodPHP5Only.htm ?

It's not complicated but you need to write a bit of code.

You can also create your own intercepting function that takes a callback and instead of calling your function/method you can pass it through your own intercepting function.

PSEUDO CODE

function myFakeFunction(...){ ... }

function runFunction($functionName){
  // DO WHAT YOU WANT: INTERCEPTION
  call_user_func($functionName);
}
runFunction("myFakeFunction", ...);

call_user_func in docs.

NOTE: you should care about security issues for both methodologies.

EDIT: I just have a new idea, you can also create a shared object for all the methods that you want to check and use _call on that object. But I'm not sure if that would work correctly.

Thursday, September 22, 2022
 
mattp
 
2

In response to the "comment-discussion" that this question (and perhaps answer) has ignited, a recap of my opinion, and the general consensus (don't skimp on equipment/server load, when that means doubling the man-hours and maintainability is more important than speed, save for a few specific cases).

You say you hate frameworks and that devs who use frameworks they didn't develop themselves sell maintainance contracts. How exactly does that work? Code using an open source, documented FW can be maintained by anyone who knows the FW. Your code can be maintained by you.
Besides, PHP frameworks are (well, the main ones at least) OPEN SOURCE. I know that, coming from a VB.NET background, you might suspect there is a catch to this, but there really isn't. They all have github repo's, the source is freely available to copy, and edit (in accordance to the license, which, on the whole is quite liberal anyway). Basically, you have full control.
And don't go thinking it's all second-grade code: Apple (including major parts of their OSX kernel), Microsoft, Google... they are all using open-source software and frameworks. Not only because it's easy, and faster to develop, but also because of the notion of proven technology.

Besides: performance is your goal, and -given that you loathe frameworks-, why not consider learning assembly? That way, you can avoid having an idiotic compiler compile your code to something that isn't as efficient as, perhaps, it could have been.
And of course, you don't use an IDE for this, you'd either go for Emacs or butterflies, right?


(source: andreas-wilm.com)

An alternative approach would be to use a framework that offers advanced caching featrures...

Maintainability should be at the most important thing to you, while writing code:

'Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.' — Brian Kernighan

Servers are zombie-slaves: they don't complain, and it's not illegal to whip them. Developers, though some project-managers seem to forget this, are neither zombies or slaves: they can't work 2 weeks on end, and whipping devs is illegal, still. Even Steve Ballmer knows that... Developers, Developers, Developers. Microsoft's Server OS's are resource intensive, as is MSSQL, and pretty much all their software, but look into their server OS. There are many features that only serve to reduce the maintainance hours your system requires. I'm no MS fan-boy, but I fully understand that descision. They can't beat Linux on price ('cause it's free), but they can lure in companies by selling a system, that will cut their sys-admin costs in half. (though, ATM, they haven't acchieved this, and IMO, they never will)


This question is one of many dupes, a bad fit for SO, and will be closed. However, before it gets closed/deleted, I'd like to point a couple of things out to you:

First things first:

As I'm currently working on an e-commerce website, I'd like to know if it's really useful to use a singleton pattern on my PDO connections

No, it never is.

PHP is not capable of persisting an objects' state in between requests. The server receives a request. The script is parsed, the DB connection is established, queries are performed, the response is sent back and the connection is closed. Over and over again.
Connections can't be serialized, they can't be stored in any way, shape or form, so:
By coding well, you can use injection and at the same time ensure that you only connect to the DB once per request.
Statics are globals in drag, now: would you use globals if you might as well pass an argument? Giving you the benefit of the doubt, I assume your answer is no.
The few remaining benefits of singletons that remain, then, are not worth the effort it takes to write decent, working, unit-tests for your singleton-using code.

Why:

my architecture is made in a way that each script only needs one connection.

Then your code isn't very scalable. I know this is a blanket statement, and a terrible cliché, but it just is the case here. Just like your presumtion that each script only needs one connection might be true right now, but who's to say that will always be the case?
Refactoring the DB, adding support for another adapter, testing (as mentioned before) become increasingly difficult, as you'll write code and, without noticing it, that new code will be adapted to maintain the singleton.
This means that you'll write code to preserve what was, because you're working around its problems, a bad design decision.

Think of it like this:
You build a house, and decide to build a concrete pilar into the corridor, because that's where you'll hang your coat-hangers anyway, and you'll never change that. But Singleton implies that you're writing OO code. The whole point is that you can re-use code. Now: do you honestly think that you'll be able to sell your house just as easily if it had an immovable coat-hanger, as it would be if that thing wouldn't be there? of course not!

And I'm quite sure that it's only useful when you have to call an instance twice or more.

If that's so: use another pattern, or take a leaf out of the Symfony book, and make the connection available to whatever object needs it using a container (dependency injection component is worth a google search).

Testing:

It's all been explained before, but testing singleton code is a nightmare. Learn to use injection.

Monday, November 21, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :