PHP static variables memory usage - php

I have been wondering for a while already how does static variables work regarding memory use and should that even be really considered?
I understand that static variables will only use up one area of memory, doesn't matter how many instances there are of the class itself. So in this sense, it should be wise to use static variables for wise memory consumption too, right? But I've never stumbled across anyone talking about the memory usage of static variables (only that you can share the data with different instances).
For example:
class Something () {
static $DB = null;
__construct ($DB) {
$this->DB = $DB;
}
}
If I would create 10 instances of this class, then it would generate less memory usage, than with non-static $DB-variable, right?
And if it is so, is the effect so small, it doesn't really matter?

and should that even be really considered?
No you shouldn't worry about statics for that reason.
The reason you have to worry about the use of static is the fact that you cannot unit test your code anymore and you have tightly coupled classes and code to Something::DB (i.e. the Something class) and you are working with global state.
Also check out an previous answer by me about how to handle those "global" instances: Which is the best practice to access config inside a function?

In your case, please, rethink your software design. In case of using static variables - you are trying (if its not, so why you need static?) to make something accessible from one place, without recreating it, like using Singleton pattern for making single instance of db object.
But if we are talking about memory usage, so yes, if you will create more objects, so you duplicating the variables - it will take more memory, but there are no real change in memory usage about its static or not.

Yes, a static attribute of a class would be stored in a single instance of memory.
But, that is not a concern in making a decision in having a variable as static. They are used for class level information such as to keep a count of the instances of a class.
Go through the following Stackoverflow post on when to use static variables:
When do I use static variables/functions in php?

You should use
self::$DB
to access static variables (as $this has no meaning in a class wide context)
Should use static for something that all objects of that class share.
You should not use parameters from the constructor to create static variables. Doing so the static variable gets overwritten when you create a new object of that type

Related

What is the difference between static functions and function outside of a class in PHP?

I need to have method to get something from a database, but I don't understand the difference between static and normal functions in PHP.
Example code
class Item {
public static function getDetail($arg) {
$detail = $this->findProductId($arg);
return $detail;
}
private function findProductId($id) {
//find product_id in database where id = $arg
//return detail of product
}
}
and function outside of a class
function getDetail($arg) {
$detail = findProductId($arg);
return $detail;
}
If I use $item = Item::getDetail(15); and $item = getDetail(15); — they're the same.
What is the difference between static and function outside of a class?
If they are difference, How to use static function and function outside of a class? (I'd appreciate a really simple example.)
What are the performance properties between static and function outside of a class? Which is better?
1) What is difference between static function and normal function
While they are functions, I'd prefer to call them methods of a given class. One is a static method and the other is an instance method.
Static Method: $item = Item::getDetail(15);
Instance Method: $item = getDetail(15);
(refer to FuzzyTree's correct syntax above in the comments, however.)
2) How to use static function and normal function (if you simple exemplify is good)
Static means you do not have to instantiate (declare an object reference). That is, you can simply use the method. So, in your example, while the answer may be the same, the way you called that method/function is different, as you noted above.
In Java, for example, you have the Math class. It does not require instantiation to use, and in fact you cannot that I know of because its constructor is private. You can simply use a method by referencing the class and the method name you wish to use,
Math.pow(d1, d2); //no instantiation needed
in PHP this might be,
MyClass::pow(d1,d2); //no instantiation needed
Java: when to use static methods
3) Ask performance between static function and normal function. Which is better?
Better is a matter of your design. If you have to create an object every time you want to do the power of a number that will create more memoryusage than simply using the class directly. I do not have benchmark proof, but it seem logical since you are not handling the method the same way in memory. I do not think it will matter in real world unless you are doing a lot of complicated actions.
Performance of static methods vs instance methods
might also interest you.
I'm assuming you're asking about the difference between a static method:
class Item {
public static function getDetail($arg){}
}
And a function written outside of a class definition:
function getDetail($arg){}
Static methods should be used over functions written outside of a class for organizational reasons. In an application with many files, having Item::getDetails($arg) will give a hint of where that function is defined. Also, having just a function written outside of a class runs the risk of name collision, if you start writing many functions outside classes.
Especially if you are writing in the OOP style, you should be using static methods over functions outside of class definitions, but I think even in general, using static methods is the better way to go.
The difference about static and non static functions is a big answer and we have to look at Object Oriented Programming (OOP) in general.
OOP in general, as you should know, is about Classes and Object, a class describe and creates objects based of it's description.
If you tell the class to contain the function "A" the object will have a callable function "A" who will have access to the objects parameters.
However if you tell the class to have a static function you tell the class to have a callable function WITHOUT instantiate an object.
Confusing? Can be at first and hard to understand why it's sometimes needed when you take your first OOP steps. Static functions is a good way to share info about classes without the need to make an object.
An analgy would be:
Take the class Car and the object BMW.
the objects functions is about THE BMW, a static functions is about cars in general.
As of performance, it's not about performance at all, it's about design patterns. So performance-wise there is nothing to gain if the functions is static or non static.
1.Entire difference is, you don't get $this supplied inside the static function. If you try to use $this, you'll get a Fatal error:
Static functions are associated with the class, not an instance of the class
and You will get an E_strict warning in the second case.
2.Now static calling of non-static methods works but is deprecated. so use normal function.
3.Technically speaking Static methods and variables are useful when you want to share
information between objects of a class, or want to represent something
that's related to the class itself, not any particular object.
For some reason, PHP allows you to call non-static and static methods
interchangeably,So performance wise or in whatever way you may say just use a normal function.Static is not going to help you at all
The difference between static and non static is that you can access a static method without having an instance of the class.
$item = getDetail(15); shouldn't work because detDetail is a method in a class and not a function.
Performance of Static Methods
There used to be a big penalty when calling a static method - but it's fixed in 5.4.0. See http://www.micro-optimization.com/global-function-vs-static-method
From what the other guy said, if it uses more memory one way versus the other it will absolutely cause a performance difference. If you're using so much memory to the point of going into GC, it can cause queuing of processes due to backup, due to gc and take the whole system down potentially if it's an enterprise system with thousands of concurrent users. It may depend on the scale of the application.
We should never be of the opinion that a change in memory utilization is "minor". It's never minor in big systems...

Is good to use static variable inside a PHP class method

I am doing a class "Container" to hold all my model/service instances, the class is a singleton.
Consider the following code portion (from a CodeIgniter project):
public function getReviewModel()
{
static $loaded = false;
if (!$loaded)
{
$this->load->model('review_model');
$loaded = true;
}
return $this->review_model;
}
I am wondering if is still ok to use static inside method like this or should I use only class property (I mean about performance and coding standard) ?
In your example, nothing prevents the programmer to instanciate the class more than once (with dire results), so it is rather a confusing bit of code.
Static variables have their uses, be them local to a function or defined at class level.
Especially in PHP scripts, when the output is often a single piece of data that can conveniently be handled as a class defining only static properties and methods.
That would be a true, foolproof singleton class.
Since mistaking a static variable for a dynamic one is a common pitfall, I tend to favor static class variables to avoid the confusion (i.e. the self::$... syntax makes them stand out clearly).
General consensus as far as statics are concerned in PHP is: Avoid, if at all possible. And yes, 99% of the time, it is possible to avoid statics.
Singletons should be avoided 100% of the time. For reasons you can find here and virtually everywhere else on the web. Singletons are like communism: sounds like a nice idea, but when put in to practice, it turns out there's one or two things you didn't anticipate.
A Singletons' main purpouse is to retain state, but PHP itself is stateless, so come the next request, the singleton needs to be re-initialized anyway.
If I write getters like yours, I tend to create them in a lazy-load kind of way:
class Example
{
private $reviewModel = null;//create property
public function getReviewModel()
{
if ($this->reviewModel === null)
{//load once the method is called, the first time
$this->reviewModel = $this->load->model('review_model');
}
return $this->reviewModel;
}
}
This basically does the same thing, without using statics. Because I'm using a property, I still retain the instance, so if the getReviewModel method is called again, the load->model call is skipped, just as it would be using a static.
However, since you're asking about performance as well as coding standards: statics are marginally slower than instance properties: Each instance has a HashTable containing for its properties, and a pointer to its definition. Statics reside in the latter, because they are shared by all instances, therefore a static property requires extra lookup work:
instance -> HashTable -> property
instance -> definition -> HashTable -> property
This isn't the full story, check answer + links here, but basically: the route to a static propery is longer.
As for coding standards: They exist, though still unofficial, most major players subscribe to them, and so should you: PHP-FIG
Things like $this->_protectedProperty; don't comply with the PSR-2 standard, for example, which states, quite unequivocally:
Property names SHOULD NOT be prefixed with a single underscore to indicate protected or private visibility.

Why are member variables usually private?

I just started to learn object oriented programming today and just by observation noticed that in all examples, member variables are private. Why is that usually the case?
// Class
class Building {
// Object variables/properties
private $number_of_floors = 5; // These buildings have 5 floors
private $color;
// Class constructor
public function __construct($paint) {
$this->color = $paint;
}
public function describe() {
printf('This building has %d floors. It is %s in color.',
$this->number_of_floors,
$this->color
);
}
}
Also, if you declare the member variable to be public, what is the syntax for accessing it outside of the class it was declared in?
And finally, do you have to prepend "public" or "private" to every variable and function inside a class?
EDIT: Thanks all for your answers, can anyone please confirm if you have to prepend "public" or "private" to every variable and function inside a class?
Thanks!
Rule of thumb is to try to hide information as much as possible, sharing it only when absolutely necessary.
Russian coders sometimes say Public Morozov at unnecessarily wide access modifiers, alluding to a story about improper information disclosure and about further punishment caused by that - Pavlik Morozov:
a 13-year old boy who denounced his father to the authorities and was in turn killed by his family...
Private variables can't be accessed from outside, that gives you control.
But if you put them Public then you can access it lke this
$your_object_instance->Your_variable
For example
$building = new Building();
echo $building->number_of_floors;
but you have to put your number_of_floors variable to public, if you want to access private member then you need to implement new method in Building class
public function getNumberOfFloors()
{
return $this->number_of_floors;
}
so your code should look like this
$building = new Building();
echo $building->getNumberofFloors();
It's to make the coding easier for you, and to make you less likely to make mistakes. The idea is that only the class can access its private variables, so no other classes elsewhere in your code can interfere and mess something up by changing the private variables in unexpected ways. Writing code like this, with a bunch of autonomous classes interacting through a small number of strictly controlled public methods, seems to be an easier way to code. Big projects are much easier to understand because they are broken up into bite sized chunks.
Making variables private keeps calling code from depending on the implementation details of your class so you can change the implementation afterward without breaking the calling code.
You can declare more than one variable on the same line and only use private or public once:
private $number_of_floors = 5, $color;
See also PHP docs' "Classes and Objects".
Senad's answer is correct in that it is good programming practice to make variables you do not want exterior methods to access private.
However, the reasoning for it in memory managed/garbage collected languages is that when you maintain a reference to an object, it is not able to be garbage collected, and can cause memory leaks.
Hope this helps!
I really dont know how to answer such question, but i describe u the best as per php manual
The visibility of a property or method can be defined by prefixing the
declaration with the keywords public, protected or private. Class
members declared public can be accessed everywhere. Members declared
protected can be accessed only within the class itself and by
inherited and parent classes. Members declared as private may only be
accessed by the class that defines the member.
Property Visibility
Class properties must be defined as public, private, or protected. If
declared using var, the property will be defined as public.
Methods declared without any explicit visibility keyword are defined as public.
for more information see Visibility
It's to prevent properties from being directly manipulated from the outside and possibly putting the object into an inconsistent state.
One of the fundamentals of OOP is that an object should be responsible for maintaining its own state and keeping it internally consistant, for example not allowing a property that's only meant to hold positive integers from being set to -343.239 or making sure an internal array is structured properly. A sure fire way of doing this is make it impossible for the values of properties to be directly set from the outside. By making the property private, you're preventing outside code from manipulating it directly, forcing it to go through a setter method that you have written for the job. This setter can do checks that the proposed change won't put the object into an inconsistent state and prevent any changes that would.
Most books and examples aimed at beginners tend to use very simple objects so it may not make sense as to why you need to go through all the private properties and getters and setters molarchy, but as the complexity of an object increases, the benefits become increasingly obvious. Unfortunately, complex objects are also not much good as teaching aids for beginners, so this point can be easily lost at first.

Alternative to regular PHP Class

Generally when creating a PHP class I would do something as such
class Foo
{
public function Foo(){}
public function RandomFunction(){};
}
global $foo;
$foo = new Foo();
$foo->RandomFunction();
I have noticed that on the web people are frowning upon the global vars for classes but without it I would not be able to access the class inside other functions.
Now an alternative to this would be using static classes as such:
class Foo
{
static public function RandomFunction(){}
}
Foo::RandomFunction();
My Question is this, is this the best alternative to global vars for classes? Or is there a better way to go about it all together?
In good OO practice, if a class needs to access an instance of another class, you pass object in as a parameter and then access it's properties and methods from there.
If you have a well designed object model the code should be relatively clean and logical, however if you aren't planning on creating a strict OO application, you probably shouldn't worry about your classes being in global scope or not.
Think of your object like a bicycle. You own your bicycle, and can loan it to whomever you wish. They can use it and return it to you, and you will be able to keep track of who did what to your bike, and when.
If your bike is generally available to anyone in the world, however, your job of monitoring and controlling access to it will become exponentially more difficult. You will be hard-pressed to keep track of who is using your bike, when they are using it, and how they are (ab)using it.
Passing your objects (rather than declaring them globally) allows you to maintain stricter controls on your object and the data it contains.

PHP - Where is the best place to initiate a database class?

I recently took my Db initiating code out of the __construct of my Page class and placed it just after I initiate the Page class. I removed it from within the Page class because I want to be able to access it from anywhere (other classes for example). It also takes server, username, password and database arguments to it when initiated, and I don't wish to enter these every time.
Is there a way I can access it from under the Page class now? I've tried a few methods, even global (which I have been told is an awful way to do things) and so far no avail. I am still new to OO, but I am teaching myself as best as I can.
Should I make it a static class? Will this affect the lazy connector to the Db I have setup?
Any help would be much appreciated.
Thank you
[EDIT]
Similar Question: Global or Singleton for database connection?
A global of some sort (Be that global variables, singleton or some other variant) is an improvement over your previous approach, and as such you're on the right track. Generally speaking though, you should try to minimise the scope of program state (For a number of reasons, which I won't get into here). Having a global variable is in conflict with this principle. There are different solutions to this problem, but the most powerful and often overlooked approach, is to use inversion of control; Instead of obtaining a dependency, your class should receive it. For example, let's say you currently have this
class EditUserController {
function saveUser() {
$db = Database::GetInstance();
$db->execute("update users set ...", ...);
}
}
You could change this into:
class EditUserController {
function saveUser($db) {
$db->execute("update users set ...", ...);
}
}
Passing dependencies on the function-parameter level can be a bit unwieldy though, so a compromise could be to pass it on a per-object level:
class EditUserController {
protected $db;
function __construct($db) {
$this->db = $db;
}
function saveUser() {
$this->db->execute("update users set ...", ...);
}
}
This is a fairly common pattern in OO programming. In addition to being more practical than passing in function parameters, it has the additional benefit of separating construction (Where shared dependencies are wired up to each other), from runtime (Where they are used). This makes a lot of things simpler.
Global variables do have a use, and this would be one of them. Unless it's likely that you're going to be needing multiple database connections, (or even still), then I don't see a problem with setting up a global $db object.
An alternative way is to have a static "Factory" class which you can use to get the object. In Joomla 1.5, the way you access the DB object is like this:
$db =& JFactory::getDBO();
the getDBO function checks if the DB object has been created: if it has, return a reference to it, otherwise connect and initialise, and then return it.
This could equally apply to other "could-be-made-global" objects, like the current User object.
The singleton method was created to make sure there was only one instance of any class. But, because people use it as a way to shortcut globalizing, it becomes known as lazy and/or bad programming.

Categories