Answer the question
In order to leave comments, you need to log in
How can I get class parameters from any section of PHP code?
Hello dear users.
Let's say we have a USER
class.
This class, when it first accesses the class, makes a request to the MySql database from where it receives the user's personal data, settings, access level, and so on. Subsequently, we can refer to our class from any part of the code when we need to get certain data associated with our user.
The question arises how to implement this class that can be used in other classes without declaring it anew in each new class.
As I understand it, inheritance and declaring a class inside another class will result in the execution of a new instance of the class.
What are the ways to solve this issue? As I understand it, there are several options, namely the registry pattern, singleton ... which way is the most suitable?
Thanks in advance, I would appreciate any useful information.
Answer the question
In order to leave comments, you need to log in
A security component that can grant access to the current user's instance. In order not to create everything by hand, use Dependency Injection. For example PHP-DI. That is, if some component needs access to the current user, we simply specify the security component in the dependencies that has the getUser method. As a result, if this component of ours is needed somewhere else, we already write it down as a dependency. Everything related to dependency resolution falls on the shoulders of our DI container.
You can learn more by reading about the "Dependency Inversion Principle".
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question