The code below is how I used to cache objects in Java.
class Account{
private static ArrayList<Account> accounts = new ArrayList<Account>(); //Array that holds Account objects
private String username; //Unique Name or Username
public Account(String username) { // constructor
this.username = username;
Account.accounts.add(this); //Add object to accounts Array
}
public String getUsername() {
return this.username; // Return username
}
public Account getAccount(String username) { //Get object "Account" with username
for (Account acc: Account.accounts) { //Foreach loop that loop over all accounts from the Array
if (acc.getUsername() == username) return acc; // Return Account object if given username == object's username
}
return null;
}
}
I commented it so it will make sense if you don't understand Java but Java OOP is similar to PHP OOP.
From the Java code above I can hold all objects on an Array, So it doesn't query the Database all the time.
1) I'm wondering if I can do something similar with PHP to speed up code and cache classes. If this is possible can you please show me an example. If not what would be the best way to achieve this?
2) What are some good practices to use when object oriented programming to keep memory usage low?
Thanks in advance