Wie kann man in PHP eine Klasse nur einmal pro kompletter Seite initialisieren?
Um sicherzustellen, dass eine Klasse in PHP nur einmal pro kompletter Seite initialisiert wird, können wir eine statische Variable innerhalb der Klasse verwenden, um zu überprüfen, ob die Initialisierung bereits erfolgt ist. Wenn die Variable bereits gesetzt ist, wird die Initialisierung übersprungen. Dadurch wird sichergestellt, dass die Klasse nur einmal pro Seite initialisiert wird.
class MyClass {
private static $initialized = false;
public function __construct() {
if(!self::$initialized) {
// Initialisierungscode hier
self::$initialized = true;
}
}
// Weitere Klassenmethoden hier
}
// Beispiel für die Verwendung der Klasse
$myObject = new MyClass();
Keywords
Related Questions
- What are the potential issues with using MySQL and PHP together for graph visualization on a website?
- Are there best practices for handling long-running shell commands in PHP scripts?
- Are there any specific PHP functions or techniques that can be used to change the appearance of past dates, such as making them smaller or changing their color?