Get and set (private) property in PHP as in C# without using getter setter magic method overloading

拜拜、爱过 提交于 2019-12-03 15:00:38

Nope.

However what's wrong with using __get and __set that act as dynamic proxies to getName() and setName($val) respectively? Something like:

public function __get($name) { 
    if (method_exists($this, 'get'.$name)) { 
        $method = 'get' . $name; 
        return $this->$method(); 
    } else { 
        throw new OutOfBoundsException('Member is not gettable');
    }
}

That way you're not stuffing everything into one monster method, but you still can use $foo->bar = 'baz'; syntax with private/protected member variables...

ReflectionClass is your salvation

I know it's too late for Hendra but i'm sure it will be helpfull for many others.

In PHP core we have a class named ReflectionClass wich can manipulate everything in an object scope including visibility of properties and methods.

It is in my opinion one of the best classes ever in PHP.

Let me show an example:

If you have an object with a private property and u want to modify it from outside

$reflection = new ReflectionClass($objectOfYourClass);
$prop = $reflection->getProperty("PrivatePropertyName");
$prop->setAccessible(true);
$prop->setValue($objectOfYourClass, "SOME VALUE");
$varFoo = $prop->getValue();

This same thing you can do with methods eighter;

I hope i could help;

If using magical properties doesn't seem right then, as already pointed out by other posters, you can also consider ReflectionClass::getProperty and ReflectionProperty::setAccessible.

Or implement the necessary getter and setter methods on the class itself.

In response to the language features issue that you raised, I'd say that having a dynamically typed language differ from a statically typed one is expected. Every programming language that has OOP implements it somewhat differently: Object-Oriented Languages: A Comparison.

luis
class conf_server
{

private $m_servidor="localhost";
private $m_usuario = "luis";
private $m_contrasena = "luis";
private $m_basededatos = "database";

public function getServer(){
    return $this->m_servidor;
}
public function setServer($server){
    $this->m_servidor=$server;
}
public function getUsuario(){
    return $this->m_usuario;
}
public function setUsuario($user){
    $this->m_usuario=$user;
}
public function getContrasena(){
    return $this->m_contrasena;
}
public function setContrasena($password){
    $this->m_contrasena=$password;
}
public function getBaseDatos(){
    return $this->m_basededatos;
}
public function setBaseDatos($database){
    $this->m_basededatos->$database;
}
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!