Can override __get from outside of a class - php

I have a class which contains a __geter which will return a computed value.
The __geter in my class could look like this:
public function __get($name) {
switch ($name) {
case "OnePlusOne":
return (1 + 1);
break;
default:
return null;
break;
}
}
Then I use my class:
$aclass = new MyClass();
$aclass->OnePlusOne = 5;
echo ($aclass->OnePlusOne); /* returns 5 instead of 2 */
How to make sure that it is not possible to change my class in this way?

You can add a __set() method that prevents any property you have defined as computed from being set.
public function __set($name, $value)
{
$computedProperties = ["OnePlusOne"];
if (!in_array($name, $computedProperties)) {
$this->$name = $value;
}
}

Related

Unable to __set() a protected var

I am trying to get the script below on __set() to update the protected var.
I want this variable to be available to everyone, not just for one instance of the class object.
So far I can only get it to work for one instance, not globally.
class SessionClass
{
protected $ssnuid = 11;
protected $paccid = 11;
protected $authkey = 11;
public function __set($name, $value){
switch ($name) {
case 'ssnuid':
$this->$ssnuid = $value;
echo $ssnuid;
break;
case 'paccid':
$this->$paccid = $value;
echo $paccid;
break;
case 'authkey':
$this->$authkey = $value;
echo $authkey;
break;
}
}
public function __get($name){
return $this->name;
}
// END CLASS
} $session = new SessionClass;
$session->ssnuid = 20;
echo $session->ssnuid;
How can I achieve this?
*Newb here so please be kind. Thanks.

php declare public variable inside function

I want to declare a variable inside a class with an unknown name
class Example {
function newVar($name, $value) {
$this->$name = $value;
}
}
And I want to use it that way
$c = new Example();
$c->newVar('MyVariableName', "This is my Value");
echo($c->MyVariableName);
The Important thing is, that I do not know the name of the variable. So I cannot put a public $MyVariable inside the class.
Is that in anyway possible? and if yes, can i do this with different scopes (private, protected, public) ?
U should use magic methods __get and __set (example without checking):
class Example {
private $data = [];
function newVar($name, $value) {
$this->data[$name] = $value;
}
public function __get($property) {
return $this->data[$property];
}
public function __set($property, $value) {
$this->data[$property] = $value;
}
}
$c = new Example();
$c->newVar('MyVariableName', "This is my Value");
echo($c->MyVariableName);
// This is my Value
$c->MyVariableName = "New value";
echo($c->MyVariableName);
// New value
See http://php.net/manual/en/language.oop5.magic.php
If i am understanding this correctly you can tweak a little bit by using key value array
class Example {
private $temp;
function __construct(){
$this->temp = array();
}
function newVar($name, $value) {
$this->temp[$name] = $value;
}
function getVar($name){
return $this->temp[$name];
}
}
$c = new Example();
$c->newVar('MyVariableName', "This is my Value");
echo($c->getVar('MyVariableName'));
Instead of using private you can use protected as well.
Your looking for magic calling. In PHP you can use the __call() function to do stuff like that. Have a look here: http://www.garfieldtech.com/blog/magical-php-call
Off the top of my head, something like
function __call($vari, $args){
if(isset($this->$vari){
$return = $this->$vari;
}else{
$return = "Nothing set with that name";
}
}
This will also work for private, protected and public. Can also use it to call methods as required in a class

How to access multiple properties with magic method(__get & __set)?

I recently studied magic methods, __get and __set, and was wondering how to actually set and get multiple properties in the class.
I know it works perfectly with only one variable or array, but I'm not sure about accessing multiple variables.
Is there anyone who could explain this to me?
class myMagic2 {
public $data;
public $name;
public $age;
public function __set($item, $value) {
$this->item = $value;
}
public function __get($item){
return $this->item;
}
}
Is there a way to access all variables ($data, $name, $age)?
When i work at projects i always have these methods:
public function __set($name, $value)
{
//see if there exists a extra setter method: setName()
$method = 'set' . ucfirst($name);
if(!method_exists($this, $method))
{
//if there is no setter, receive all public/protected vars and set the correct one if found
$vars = $this->vars;
if(array_search("_" . $name, $vars) !== FALSE)
$this->{"_" . $name} = $value;
} else
$this->$method($value); //call the setter with the value
}
public function __get($name)
{
//see if there is an extra getter method: getName()
$method = 'get' . ucfirst($name);
if(!method_exists($this, $method))
{
//if there is no getter, receive all public/protected vars and return the correct one if found
$vars = $this->vars;
if(array_search("_" . $name, $vars) !== FALSE)
return $this->{"_" . $name};
} else
return $this->$method(); //call the getter
return null;
}
public function getVars()
{
if(!$this->_vars)
{
$reflect = new ReflectionClass($this);
$this->_vars = array();
foreach($reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED) as $var)
{
$this->_vars[] = $var->name;
}
}
return $this->_vars;
}
So with them i give myself the freedom to create extra setter/getter for properties if i want to manipulate them before writing/returning. If no setter/getter exists for the property it falls back to the property itself. With the method getVars() you receive all public and protected properties from the class.
My class properties are always defined with an underscorce so you should probably change that.
You could follow this pattern.
Note: in the example in the post the magic methods would not have been called for $obj->data, $obj->name, or $obj->age because these values where already accessible as a public property. I changed them to be protected and altered the name to hide them.
<?php
class myMagic2{
protected $_data;
protected $_name;
protected $_age;
public function __set($item, $value){
switch($item){
case "data":
$this->_data = $value;
break;
case "name":
$this->_name = $value;
break;
case "age":
$this->_age = $value;
break;
default:
throw new Exception("Property $name does not exist.");
}
}
public function __get($item){
switch($item){
case "data":
return $this->_data;
break;
case "name":
return $this->_name;
break;
case "age":
return $this->_age;
break;
default:
throw new Exception("Property $name does not exist.");
break;
}
}
}
Normally you would do a little more then use the magic methods as a proxy to set and get classes properties. You would so validation or filtering or in some other way augmenting the operation. If you are just going to get or set a property you might as well just make the properties public and forgo using the magic methods.

PHP: immutable public member fields

I need to create an immutable class which is simply a member field container. I want its fields to be instantiated once in its constructor (the values should be given as parameters to the constructor). I want the fields to be public but immutable. I could have done it with Java using the final keyword before each field. How is it done in PHP?
You should use __set and __get magic methods and declare that property as protected or private:
/**
* #property-read string $value
*/
class Example
{
private $value;
public function __construct()
{
$this->value = "test";
}
public function __get($key)
{
if (property_exists($this, $key)) {
return $this->{$key};
} else {
return null; // or throw an exception
}
}
public function __set($key, $value)
{
return; // or throw an exception
}
}
Example:
$example = new Example();
var_dump($example->value);
$example->value = "invalid";
var_dump($example->value);
Outputs:
string(4) "test"
string(4) "test"
#property-read should help your IDE acknowledge existence of this magic property.
You could use the __set() magic method and throw an exception when someone tries to set a property directly.
class ClassName {
public function __set($key, $value) {
throw new Exception('Can't modify property directly.');
}
}
However, this would prevent modification of properties regardless of whether they're public or not.
magic methods
so you can do better - if you have a dinamyc count of fields
class ClassName {
private $fields = array();
// use class : $cl = new ClassName(array('f'=>2,'field_4'=>5,''12));
// echo $cl->field_4; echo $cl->f;
public function __construct($data= array())
{
if (!is_array($data) || !count($data)) throw new Exception('Not enough args')
foreach ($data as $key=>$val)
{
if (is_numeric($key))
$this->fields['field_'.$key] = $val;
else
$this->fields[$key] = $val;
}
}
/* in this case you can use this class like $cl = new ClassName(12,14,13,15,12); echo $cl->field_1;
public function __construct()
{
$ata = funcs_get_args();
if (!count($data)) throw new Exception('Not enough args')
foreach ($data as $key=>$val)
{
if (is_numeric($key))
$this->fields['field_'.$key] = $val;
else
$this->fields[$key] = $val;
}
}
*/
public function __get($var) {
if (isset($this->fields[$var]))
return $this->fields[$var];
return false;
//or throw new Exception ('Undeclared property');
}
}
<?php
declare(strict_types=1);
final class Immutable
{
/** #var string */
private $value;
public static function withValue(string $value): self
{
return new self($value);
}
public function __construct(string $value)
{
$this->value = $value;
}
public function value(): string
{
return $this->value;
}
}
// Example of usage:
$immutable = Immutable::withValue("my value");
$immutable->value(); // You can get its value but there is no way to modify it.

PHP: How do I check if all public methods of two classes return the same values?

In effect, if I have a class c and instances of $c1 and $c2
which might have different private variable amounts but all their public methods return the same values I would like to be able to check that $c1 == $c2?
Does anyone know an easy way to do this?
You can also implement a equal($other) function like
<?php
class Foo {
public function equals($o) {
return ($o instanceof 'Foo') && $o.firstName()==$this.firstName();
}
}
or use foreach to iterate over the public properties (this behaviour might be overwritten) of one object and compare them to the other object's properties.
<?php
function equalsInSomeWay($a, $b) {
if ( !($b instanceof $a) ) {
return false;
}
foreach($a as $name=>$value) {
if ( !isset($b->$name) || $b->$name!=$value ) {
return false;
}
}
return true;
}
(untested)
or (more or less) the same using the Reflection classes, see http://php.net/manual/en/language.oop5.reflection.php#language.oop5.reflection.reflectionobject
With reflection you might also implement a more duck-typing kind of comparision, if you want to, like "I don't care if it's an instance of or the same class as long as it has the same public methods and they return the 'same' values"
it really depends on how you define "equal".
It's difficult to follow exactly what you're after. Your question seems to imply that these public methods don't require arguments, or that if they did they would be the same arguments.
You could probably get quite far using the inbuilt reflection classes.
Pasted below is a quick test I knocked up to compare the returns of all the public methods of two classes and ensure they were they same. You could easily modify it to ignore non matching public methods (i.e. only check for equality on public methods in class2 which exist in class1). Giving a set of arguments to pass in would be trickier - but could be done with an array of methods names / arguments to call against each class.
Anyway, this may have some bits in it which could be of use to you.
$class1 = new Class1();
$class2 = new Class2();
$class3 = new Class3();
$class4 = new Class4();
$class5 = new Class5();
echo ClassChecker::samePublicMethods($class1,$class2); //should be true
echo ClassChecker::samePublicMethods($class1,$class3); //should be false - different values
echo ClassChecker::samePublicMethods($class1,$class4); //should be false -- class3 contains extra public methods
echo ClassChecker::samePublicMethods($class1,$class5); //should be true -- class5 contains extra private methods
class ClassChecker {
public static function samePublicMethods($class1, $class2) {
$class1methods = array();
$r = new ReflectionClass($class1);
$methods = $r->getMethods();
foreach($methods as $m) {
if ($m->isPublic()) {
#$result = call_user_method($m->getName(), $class1);
$class1methods[$m->getName()] = $result;
}
}
$r = new ReflectionClass($class2);
$methods = $r->getMethods();
foreach($methods as $m) {
//only comparing public methods
if ($m->isPublic()) {
//public method doesn't match method in class1 so return false
if(!isset($class1methods[$m->getName()])) {
return false;
}
//public method of same name doesn't return same value so return false
#$result = call_user_method($m->getName(), $class2);
if ($class1methods[$m->getName()] !== $result) {
return false;
}
}
}
return true;
}
}
class Class1 {
private $b = 'bbb';
public function one() {
return 999;
}
public function two() {
return "bendy";
}
}
class Class2 {
private $a = 'aaa';
public function one() {
return 999;
}
public function two() {
return "bendy";
}
}
class Class3 {
private $c = 'ccc';
public function one() {
return 222;
}
public function two() {
return "bendy";
}
}
class Class4 {
public function one() {
return 999;
}
public function two() {
return "bendy";
}
public function three() {
return true;
}
}
class Class5 {
public function one() {
return 999;
}
public function two() {
return "bendy";
}
private function three() {
return true;
}
}
You can define PHP's __toString magic method inside your class.
For example
class cat {
private $name;
public function __contruct($catname) {
$this->name = $catname;
}
public function __toString() {
return "My name is " . $this->name . "\n";
}
}
$max = new cat('max');
$toby = new cat('toby');
print $max; // echoes 'My name is max'
print $toby; // echoes 'My name is toby'
if($max == $toby) {
echo 'Woohoo!\n';
} else {
echo 'Doh!\n';
}
Then you can use the equality operator to check if both instances are equal or not.
HTH,
Rushi
George: You may have already seen this but it may help: http://usphp.com/manual/en/language.oop5.object-comparison.php
When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class.
They don't get implicitly converted to strings.
If you want todo comparison, you will end up modifying your classes. You can also write some method of your own todo comparison using getters & setters
You can try writing a class of your own to plugin and write methods that do comparison based on what you define. For example:
class Validate {
public function validateName($c1, $c2) {
if($c1->FirstName == "foo" && $c2->LastName == "foo") {
return true;
} else if (// someother condition) {
return // someval;
} else {
return false;
}
}
public function validatePhoneNumber($c1, $c2) {
// some code
}
}
This will probably be the only way where you wont have to modify the pre-existing class code

Categories