Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this just encapsulation?

Tags:

oop

php

I've this class. A plain old php object like this:

class Foo
{
    private $value;

    public function getValue()
    {
        return $this->value;
    }
}

This Foo::getValue() is used to check if Foo::$value is 'foo' or 'bar'. Instead of use these, ...

if ($foo->getValue() == 'foo') {

}

if ($foo->getValue() == 'bar') {

}

I want to expose these method.

if ($foo->isValueFoo()) {

}

if ($foo->isValueBar()) {

}

How this refactoring operation is called? I want to promote e verbose but speaking interface. I don want to expose 'foo' or 'bar' scalars. Is a good or best practice?

like image 549
sensorario Avatar asked Jun 03 '26 20:06

sensorario


1 Answers

Lets say if you have 100's of such string values for which you want to check, for that you have to exhibit such 100's function for getting this done. You can try something like __call magic function.

Here we are using __call magic method to achieve this. This is just a sample code, you can do the required changes.

With this class object you can call any method with name prefix: isValue and postfix: placeholderValueString.

for getting postfix string value you can use either this substr_replace($functionName, "", 0,strlen("isValue")) or substr($functionName, strlen("isValue"))

or Try this code snippet here

<?php
ini_set('display_errors', 1);

class Foo
{
    private $value="foo";

    public function __call($functionName, $arguments=array())
    {
        if(strpos($functionName, "isValue")===0){
            $value= strtolower(substr_replace($functionName, "", 0,strlen("isValue")));
            if($this->value==$value){
                return true;
            }
        }
        return false;
    }
}
$object= new Foo();
echo $object->isValueFoo();
echo $object->isValueBar();
like image 190
Sahil Gulati Avatar answered Jun 05 '26 11:06

Sahil Gulati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!