Should I use property handling in C # in PHP?

Hi community, I saw here: http://www.mustap.com/phpzone_post_203_setter-and-getter the argument for using the type of processing properties common to C #, that is: If in C # you can define a class as follows:

public class Person 
{
    private string _name;
    public string Name
    {
        get{ return _name; }
        set{ _name = value; }
    }
}

then why is it reasonable or not to define a similar property in php like this:

public class Person
{
    private var $name;    

    public function Name() 
    {
        if(func_num_args() == 0) {    return $this->name;  } 
        else {$this->name = func_get_arg(0);  }
    }
}
+2
source share
4 answers

IMO that doesn't look clean in PHP. It looks like you're trying to push C # into PHP because you think this is a good C # feature.

: PHP , . , # , , /.

+5

, , .

# , php.

, # ,

public string Name { get; set; }

, getter setter .

+3

, , getFoo setFoo, . / . ( - , #. , , .)

+2

, :

class Settings
{
    private $data = array();

    public function __call($key,$arguments = array())
    {
        return !count($arguments)) ? $this->data[$key] : $this->data[$key] = $arguments[0];
    }
}

$Settings = new Settings();
$Settings->name('hello');
$Settings->foo('bar');

, , __get __set , ,

class Settings
{
    private $data = array();

    public function __set($key,$val)
    {
        $this->data[$key] = $val;
    }
    public function __get($key)
    {
        return $this->data[$key];
    }
}

:

$Settings->foo = 'bar';

But you can go a little further and create a variable registry system:

so basically you can change the above class from Settingsto VariableStorageand do the following:

class User extends VariableStorage{}
class Profile extends VariableStorage{}

And use like this:

$Profile = new Profile('Robert','Pitt',USER_PRIV_ADMIN);
$Profile->id = 56;
$Profile->userdata = $Database->GetUserData($Profile); //Reads $Profile->id

So, you only need to define the methods once and until you create the inheritance structure before a good design, it can work very well.

+2
source

Source: https://habr.com/ru/post/1615263/


All Articles