This question already has answers here:
What are the advantages of using getters and setters instead of functions or simply public fields in PHP? [closed]
(15 answers)
Closed 5 years ago.
I need to know how getter and setter will work in PHP.
Because some interviewer asked tricky question about getter and setter.
I have failed to explain.
Can any one help me out?
Getters and setters are used to- at a later stage- make it possible to provide logic when the developer requests or sets a variable.
If you, for example, want to add a layer of validation to prevent your object from being misused. What if you wanted to make sure that the person’s $name variable is a string variable and not something else? Well, we can simply add that layer of validation to our setter method:
//Set the person's name.
public function setName($name){
if(!is_string($name)){
throw new Exception('$name must be a string!');
}
$this->name = $name;
}
In the PHP code above, we modified the setter method setName so that it validates the $name variable. Now, if a programmer attempts to set the $name variable to an array or a boolean, our function will throw an Exception. If we wanted to, we could also make sure that the $name variable is not a blank string.
Big thanks to this post.
Best of luck on your interview!
Related
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 6 years ago.
I'm new in OOP with PHP and I'm wondering why I can't declare an instance variable in my class so that I can use it properly. If declaring the variable like on the picture at the top, I get the error message from picture 3. If I add the "public" modifier to the variable, my PHP file says exactly nothing (No Error, just a white empty screen). It all works when I write the string directly into my function, but I wanted to try out using an instance variable.
I tried to solve this problem by myself and didn't find any solutions. So please don't be too mad about it.
Your return $name; searches for a variable $test in your function/method scope. To access the class property, you have to specify it:
class recipeapi
{
// add visibility keyword here
private $name = 'Felix';
// kind of standard is to use get...(), but return...() works the same way
public function getName()
{
// use $this->varname if you want to access a class property
return $this->name;
}
}
This question already has answers here:
Check variable is public php
(3 answers)
Closed 7 years ago.
I'm building a class. I intend for this class to be a sort of master parent class for a lot of API and database interactions later on.
Assume it looks something like this
class api_controller{
public $method = 'get';
private $table;
protected $table_id_column;
//Rest of code is really not needed
}
I was wondering if it was possible, from within PHP, to figure out if a variable is public,private, or protected if given the name? If it is, I had planned to use it as a checking station to make sure that no child methods alter data they've been restricted from accessing via an inherited method.
I had googled my question and came up with a lot of get_object_vars() vs get_class_vars() discussions, as well as a great many discussions about the difference between private, protected, and public. From my search of Object/Class functions through the PHP database, I didn't see anything that immediately jumped out at me as my answer.
I was thinking that it may have to be a try/catch statement done by accessing the variable and seeing if it throws an error (which would let me know if it was public/private), but I'm unsure of how to determine past that point. Even then, this method would have to be a member of the parent class, so it would have access to all of its own private variables.
Any Ideas?
Use Reflection:
$class = new ReflectionClass('api_controller');
$property = $class->getProperty('method');
// then you could check by
// there are also methods of isProtected, isPublic, etc...
if ($property->isPrivate()) {
// ..
}
This question already has answers here:
Why "private" methods in the object oriented?
(9 answers)
Closed 9 years ago.
Completely new to OOP programming, so sorry if the answer is obvious. I've seen many YouTube tutorials where the code is as following:
class myClass{
private $myVar;
function getVar(){
return $this->myVar;
}
}
myObject = new myClass();
print myObject->getVar();
but why is it preferable to make the variable private and then access it through a function, rather than just using myObject->myVar?
A few benefits of private variables:
Nobody can change it from the outside without your permission. If this variable is important for internal state, having somebody externally access it can be disastrous when you need to use it next (because of a different method call on your class). This is a big deal.
If somebody calls "get" on it, you can intercept it and create side effects if needed (for accounting reasons for example; note that "magic" behind the scenes is generally not a good idea from just a pure accessor).
The value returned from a "get" may not be a real concrete value, but the result of a calculation. You expose it via the method, but it doesn't really need to be cached internally.
You may also see here.
Was this helpful?
In the first case you have a getter, not a setter, so you could "read only" the private $myVar. In the second case $myVar is public so you can just set and get myVar.
Maybe read more about getter and setter (even on stackoverflow) to understand, why using getter and setter in OOP Design Pattern is more effective :)
A get and set function might do more than just get and set. For instance, how about something like this:
class myClass {
private $myVar;
public function setVar($val) {
if( !is_numeric($val)) throw new Exception("Input must be a number");
$this->myVar = 0+$val;
}
}
If $myVar were public, I could set any value I wanted, not just numbers, which could cause errors later. This is just one possible application, there are uncountably many uses ;)
The larger your projects become, the greater the number of interactions that can occur between different objects. You want to control and limit these interactions to the bare minimum else difficult to discover side effects can and will creep into your code.
For example, you can have a class to calculate taxes of given amount of money. You wouldn't want anyone to accidently change 0.05 tax amount to something like 3.00 and bill the customer triple amount of item's price, or change the type of tax variable to something like NULL and cause exceptions/fatal errors during calculation.
With a settler, you can force people to obey your rules. You can validate everything before assigning values to private variables.
Usually, a good practice approach is: make everything private - then make public what needs to be public - and add required gettlers and settlers for necessary privates.
This question already has an answer here:
Accessing variables through classes
(1 answer)
Closed 9 years ago.
I have the following class:
class validationHandler{
private $dataType; //set via constructor ...
private $validation = null;
private function requireValidation(){
if($this->validation == null){
$this->validation = loadDataFromJSONfile($this->dataType);
}
}
public function validate($data){
$this->requireValidation();
//validate... the rules are in the $validation-variable
}
}
When an object needs to validate some data, it makes a new validation-object and calls validate().
The first time something needs to be validated, the data is loaded from a json-file.
But: Sometimes I have several Objects which need the same validation-file. And This code loads the file for each Object.
Question: Is there a way to set $validation global, so that every object accesses the same variable, but without loosing the private-property?
(Notice that I have different validation-files and different kinds of objects. An objects tells the validationHanlder in __construct() which type it has, and which validation-file should be loaded. So I need $validation to be an array. (Didn't write it in the code, so it's more readable)
You want to create your variable using static, it sounds like.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I currently have my PHP class variables set up like this:
class someThing {
private $cat;
private $dog;
private $mouse;
private $hamster;
private $zebra;
private $lion;
//getters, setters and other methods
}
But I've also seen people using a single array to store all the variables:
class someThing {
private $data = array();
//getters, setters and other methods
}
Which do you use, and why? What are the advantages and disadvantages of each?
Generally, the first is better for reasons other people have stated here already.
However, if you need to store data on a class privately, but the footprint of data members is unknown, you'll often see your 2nd example combined with __get() __set() hooks to hide that they're being stored privately.
class someThing {
private $data = array();
public function __get( $property )
{
if ( isset( $this->data[$property] ) )
{
return $this->data[$property];
}
return null;
}
public function __set( $property, $value )
{
$this->data[$property] = $value;
}
}
Then, objects of this class can be used like an instance of stdClass, only none of the members you set are actually public
$o = new someThing()
$o->cow = 'moo';
$o->dog = 'woof';
// etc
This technique has its uses, but be aware that __get() and __set() are on the order of 10-12 times slower than setting public properties directly.
If you're using private $data; you've just got an impenetrable blob of data there... Explicitly stating them will make your life much easier if you're figuring out how a class works.
Another consideration is if you use an IDE with autocomplete - that's not going to work with the 2nd method.
If code is repetitive, arrays and (foreach) loops neaten things. You need to decide if the "animal" concept in your code is repetitive or not, or if the code needs to dig in to the uniqueness of each member.
If I have to repeat myself more than once, I loop.
Use the first method when you know you need that variable.
Use the second method (an array collection of variables) when you have dynamic variable needs.
You can combine these 2 methods, so some variables are hardcoded into your class, while others are dynamic. The hardcoded variables will have preference compared with magic methods.
I prefer the first method, for a few reasons:
In a good IDE, the class properties show up, even if private/protected
It's easier to see what has already been defined, reducing the chance you store the same information twice.
If the proverbial bus hits you on the way home, it's a lot simpler for another developer to come in and read your code.
And while it doesn't apply to private var, it does to protected vars, in classes that extend this class, you really should try to avoid the second method for pure readability.
Also, as a side note, I almost always choose protected over private unless I have a very specific reason to make it private.
The only time I'd probably use the second method was if I was storing a collection of many of one kind of thing.