PHP - set and get method


PHP - set and get method

我怎么能像这样设置和获取属性。

$newObj = new Core;
$newObj->setTitle("Value"); //where title is a property from the Core object
$newObj->getTitle(); 

我是OOP新手,请帮忙。

UPDATE:与magento设置和获取会话的方式类似。

PHP为您提供了所谓的魔术方法。你有一个__get__set魔术方法。

这允许访问类的其他不可访问的属性,尽管不是通过setFoo()getFoo()方法调用。如果您希望这样做,您必须为每个属性定义2个方法,或者您可以使用第三个神奇的方法__call

您可以获得作为第一个参数调用的方法的名称,以及其他参数的数组,这样您就可以很容易地识别为哪个操作进行了调用。一个简短的例子:

public function __call($methodName, $methodParams)
{
    $type = substr($methodName, 0, 3);
    $property = lcfirst(substr($methodName, 3)); // lcfirst is only required if your properties begin with lower case letters
    if (isset($this->{$property}) === false) {
        // handle non-existing property
    }
    if ($type === "get") {
        return $this->{$property};
    } elseif ($type === "set") {
        $this->{$property} = $methodParams[0];
        return $this; // only if you wish to "link" several set calls.
    } else {
        // handle undefined type
    }
}

您可以使用简单的公共方法为类属性设置值。

https://eval.in/548500

class Core {
  private $title;
  public function setTitle($val) {
      $this->title = $val;
  }
  public function getTitle() {
      return $this->title;
  }
}

您需要一个简单的类来完成此操作。

<?php
    class Core
    {
      private $title;
      public function setTitle($val)
      {
          $this->title = $val;
      }
      public function getTitle()
      {
          return $this->title;
      }
    }
    $newObj = new Core;
    $newObj->setTitle("Value");
    $newObj->getTitle();
?>

首先创建这样的类

<?php
class sampleclass {
   private $firstField;

  public function getfirst() {
    return $this->firstField;
 }
public function setfirst($value) {
   $this->firstField = $value;
}
}
?>

之后,您可以通过生成类的对象并调用适当的方法来使用这些方法。

调用方法是这样的,

$obj = new sampleclass();
$obj->setfirst( 'value' ); 
echo $obj->getFirst(); 

就是这样。