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.
Related
For example, with a parent like this:
class Music {
private $timbre; // This?
protected $timbre; // Or this?
public function getTimbre(){
return $this->timbre;
}
}
In an inheriting child, is it OK from an OO point of view to access the member variable directly, or best to use the getters/setters?
class PostPunk extends Music {
public function doSomethingTimbreRelated(){
$punk_timbre = $this->getTimbre(); // This?
$punk_timbre = $this->timbre; // Or this?
// ... do something ...
}
}
I've read that keeping member variables private is better for encapsulation, but does that really matter in an inheritance hierarchy?
And I realize this is very trivial, but I sort of waffle back and forth to doing it both ways, so I'd like to settle in on one way
After a bit of research, now I understand that using getters/setters promotes loose coupling to the parent object, via encapsulation.
In a small project with few developers and simple classes, the benefits of this are not obvious.
However, imagine a large project with many inheriting classes, as well as external classes consuming getters/setters.
If, down the road, you need to modify or add some business logic to the value returned by the getter, you will have to rewire all of the inheritors to use the getters VS accessing the properties directly.
Same goes for the setter - perhaps you decide to add some data sanitization/validation. Directly accessing the properties will bypass these future improvements.
Analogy: Rather than letting your kid have free access to your purse/wallet, you are forcing her to ask you for money, then you decide what and how much to give her.
For my latest website I’ve been trying to use classes. Mainly to teach myself more about OOP and learn through experience.
Whenever I needed a ‘variable’ within my class I created a property, for instance:
class someClass
{
var $valueToUseHere; // Only used internally - can I just use a variable?
public function doStuff()
{
$this->valueToUseHere = 60;
// Do more stuff here...
}
}
It is only now when I’ve been looking more into the code and trying to do some optimisation that I’ve noticed that my functions and classes are passing around some large objects. A lot of that bulk could be stripped away if I made all the properties that are only used inside the class into normal variables.
Are properties only used for variables that are needed outside the class and is it then acceptable to just use ‘normal’ variables within the class itself ?
Sorry if this question illustrates a lack of understanding on the subject. Unfortunately, this is where my learning is up to at this point. I’ve done some searching around “class properties vs variables” etc but not found a comprehensive answer to this.
Many thanks
It's somewhat vague what you're asking, but if valueToUseHere is not used outside of doStuff, then don't make it a property!
class someClass {
public function doStuff() {
$valueToUseHere = 60;
// Do more stuff here...
}
}
If there's no reason to share that value with other methods of the class or with the outside world, then there's no reason to clutter up your object with all sorts of properties. Not only may this cause tricky bugs with preserved state, it also forces you to be unnecessarily careful with your variable names across all object methods.
Actually class properties are variables as well. Basically you have three options:
Global variable, available everywhere, but not recommended because all parts of your code may depend on such a varialbe, changes can easily break stuff everywhere.
Class property (Note: you should define a visibility - public/protected/private) these properties are bound to the object instance and should be used for any state that the object needs to keep for further processing. Usually those might be used in more than one metohd of your class.
Variables inside a method like just
public function doStuff()
{
$valueToUseHere = 60;
// Do more stuff here...
}
The variable is just available inside the method and is thrown away at the end of the method execution.
That depends on your needs. If you are going to simply hold a value in a variable it's the best to keep it's simplicity and not define functions for setting or getting it's value. But sometimes you may need to have more controls on a variable in your class. For example you have defined an integer variable and you want it's values to be always between 10 and 1000 and also it should not be in 100,200,300,..,900. So here there is a good reason to set your variable access to private and create a public function to check what is required before setting a new value. Or in another example you may want to call another function or change another depended variable in your class exactly after this variable changed. Or if you want to make a variable read-only or write-only always you can define properties for controlling the variable value.
In brief you may prefer to use:
Properties: When you want to have control about get and set values
Variables: When you want to set or use a variable as its nature
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...
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.
This question already has answers here:
What is the difference between public, private, and protected?
(16 answers)
Closed 9 years ago.
I have been thinking about the usage of private variables and methods in php.
I am not going to talk about a class of car or anything like that. I want to talk about an own script.
What is the difference between using public or private for the programmer and the owner of the script.
if the script is a calculator, and I am the only one who will meinten the code in the future. when do I have to use private variables of methods. How this is going to change anything in the script?
Also, If it's about touching the variable ? if anyone tries to change the value, and he couldn't because of the private thing. He will go directly to change it using the setters ?
I need a good example that I can see private methods or variables have good benefits for programmer or the end user.
I was programming some scripts, and a guy told me to not use var in classes. I asked him why ? he said that you have to use public or private .. and asked why ?
Why to use setter if there is a way to change the variable directly?
Why to use getter if there is a way to change the variable directly?
First of all, when you're developing strong-OO classes, you should be exposing as little of the internal semantics of your class as possible (obviously without affecting functionality).
Some variables are only valuable inside the context of the class itself, and would make no sense to a developer using the class. Making the variable public allows anyone using the class to change such a variable at will, despite the fact that they may not know what it's used for. In PHP this can be a particular problem when you don't even have type safety to at least mitigate the damage that can be done.
Consider this: You have a class which wraps around some I/O operations. Let's call it FileReader
class FileReader {
public $_handle;
public function __construct($filepath) {
$this->_handle = fopen($filepath, 'r');
if ($this->_handle === NULL) {
throw new Exception("Unable to open the file for reading");
}
}
// ... the rest of the class
}
Now you can see that the class opens up a handle to a file. By making the $_handle variable public, you've exposed it to any and all people working on your class. They don't need to know about the raw file handle you have open, they just want to use your nice class to perform some read operation. However, it IS public; not only can they see it, but they can change it. This is bad, especially when your other code assumes that the $_handle variable is valid.
$reader = new FileReader();
$reader->_handle = "I hope this doesn't break anything. /trololol";
$reader->someOperation(); // oh no! Our file handle has just been changed to something completely wrong, this is now going to the break the class.
Such ridiculous scenarios can be avoided entirely by making the variable private in the first place. For more (and better) example of what each access modifier does, and when to apply them see this answer.
Now, onto getters and setters. In your question, you seem to assume that all getters and setters are written the following way:
class Foo {
private $_bar;
public function getBar() {
return $this->_bar;
}
public function setBar($newBar) {
$this->_bar = $newBar
}
}
In which case, you're absolutely right there is no difference between that and changing the $_bar variable to be public in the first place.
However, getter and setter methods give you control over how your variables are being set by an external developer, so you can instantly detect when they're going to make a boo-boo and avoid undefined behaviour later on. For example:
class Foo {
private $_bar;
public function getBar() {
return $this->_bar;
}
public function setBar($newBar) {
// Now we're going to ensure that $newBar is always an integer
if (!is_int($newBar)) {
// not an integer, throw out an exception to let the developer know that somewhere is setting invalid input
throw new Exception("Expected an integer value for 'Bar'");
}
$this->_bar = $newBar;
}
}
This is not only making your class far more robust, but also making the life of the developer using your class a hell of a lot easier. Rather than having to debug an extremely weird issue somewhere later on when the class attempts to use the corrupt value of $_bar, they can easily tell from a stack trace where the corrupt value was set from and fix it at the source.
There is plenty of documentation about variable access and getter/setter methods out there, and it applies to a whole range of languages so don't be afraid to look up articles that were based on C++/C#/VB.NET, they all roughly translate to the same material.
The end user doesn't see the code, so there's no (dis)advantage there.
For the programmer, declaring things that aren't needed outside the object as private is just a good programming practice and a protection mechanism. Technically, if you're a perfect programmer, and you don't care about how your code looks, using private will provide you no benefits. However, private members enforce the black box model -- you only care about what the object does, not about how it works (when looking at it from the outside). In the end, if for any reason you (or somebody else) needs/wants to use your code, they'll know what methods and properties to use/invoke in order to get the functionality the object has, without modifying the internal values the object needs to maintain. It may or may not give you any advantage -- it's just about how the code looks like. That's what good programming practices are for, and they are usually followed because experience says they tend to minimize errors.
As for var, it was deprecated. Meaning it could (and will) be removed in the future.
Public, Private and Protected only matter in PHP if they are part of a function, or part of a class.
If you wanted to set a variable once and "lock it" so the value couldn't be changed later you can define it or set it as a const (constant).
public scope to make that variable/function available from anywhere,
other classes and instances of the object.
private scope when you want your variable/function to be visible in
its own class only.
protected scope when you want to make your variable/function visible
in all classes that extend current class including the parent class.
See here: http://php.net/manual/en/language.oop5.visibility.php