方法中的php类方法

时间:2017-02-13 07:34:14

标签: php zend-framework php-7 object-oriented-analysis

如果我想访问公共方法,我可以轻松地做到这一点。但是如果我想在方法中访问该属性,我该怎么做,是否推荐??

我可以在php中做这样的事情吗?

class Auth {
   public function check($user = false){
    $project = false; //make it somehow public
     if($user == 'user1'){
       $this->project = 1;
     }
   }
}

而不是其他地方

$auth = new Auth();
$auth->check('user1')->project;

这样,人们就知道它可能来自

Zend framework代码
  

Zend-Authentication

 if ($result->isValid()) {
            $this->getStorage()->write($result->getIdentity());
        }

6 个答案:

答案 0 :(得分:3)

$(document).delegate('#cover-image','change', function(e){
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#Image1').attr("src", e.target.result);
                var $img = $("#Image1");
                $img.hide().removeClass("image12");
                var w = $img.width();
                var h = $img.height();
                $('#Image1').Jcrop({
                    trueSize: [w, h],
                    onChange: SetCoordinates,
                    onSelect: SetCoordinates
                });
            }

            reader.readAsDataURL($(this)[0].files[0]);      
        });

<style type="text/css">
.image12{
   height:600px; 
   width:600px;
}
</style>

<img id="Image1" class="image12" src="" alt="" style="display: none; " />

然后您可以执行以下操作:

class Auth
{
   protected $project;

   public function __constructor($project = false)
   {
        $this->project = $project;
   }

   public function check($user = false)
   {
     if($user == 'user1')
     {
       $this->project = 1;
     }

      return $this;
   }

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

或者如果您愿意,还可以在构造函数

中为$auth = new Auth(); $auth->check('user1')->project(); // returns 1 设置另一个默认值
$project

答案 1 :(得分:3)

我相信您的问题基本上与Fluent Interfaces或方法链接结合使用魔术方法__get

试图运行:

<?php
class Auth {
   public function check($user = false){
    $project = false; //make it somehow public
     if($user == 'user1'){
       $this->project = 1;
     }
   }
}

$auth = new Auth();
$auth->check('user1')->project;

结果:

  

注意:尝试在第13行的/ in / Hi5Rc中获取非对象的属性

因为$auth->check('user1')返回NULL(或void),而NULL没有project属性。

我们要求的第一件事是让$auth->check('user1')返回一些有用的东西。鉴于$project是一个布尔值,而$this->project是一个整数,最有意义的是返回$project并获取值。

<?php
class Auth {
   public function check($user = false){
    $project = false; //make it somehow public
     if($user == 'user1'){
       $this->project = 1;
     }
    return $project;
   }
}

$auth = new Auth();
print_r($auth->check('user1'));

导致:

  

布尔(假)

但是这并没有解决你如何流利地访问非公共字段或参数的问题。

您似乎在错误地认为这些项目正在$project类中使用方法作用域变量(如check())并使其可访问。他们不是。

甚至没有Zend-Authentication的例子。

字段$storage本身受到保护,但它具有公开(流利)getters/setters

因此,$this->getStorage()会返回new Storage\Session()的实例,其中包含公开write()

因此$this->getStorage()->write()有效。

所以让我们拿你的示例类并稍微修改一下来演示。

<?php
class Project{
    /**
     * @var string
     */
    private $name;
    /**
     * @var bool
     */
    private $active;
    /**
     * @var string
     */
    private $description;

    public function __construct($name = 'Default', $active = false, $description = '')
    {
        $this->name = $name;
        $this->active = $active;
        $this->description = $description;
    }

    /**
     * @param string $name
     *
     * @return Project
     */
    public function setName(string $name): Project
    {
        $this->name = $name;

        return $this;
    }

    /**
     * @param bool $active
     *
     * @return Project
     */
    public function setActive(bool $active): Project
    {
        $this->active = $active;

        return $this;
    }

    /**
     * @param string $description
     *
     * @return Project
     */
    public function setDescription(string $description): Project
    {
        $this->description = $description;

        return $this;
    }

    /**
     * @return string
     */
    public function getName(): string
    {
        return $this->name;
    }

    /**
     * @return bool
     */
    public function isActive(): bool
    {
        return $this->active;
    }

    /**
     * @return string
     */
    public function getDescription(): string
    {
        return $this->description;
    }

    public function toArray(){
        return [
            'name' => $this->name,
            'active' => $this->active,
            'description' => $this->description
        ];
    }

    public function toJson(){
        return json_encode($this->toArray());
    }

    public function __toString()
    {
        return $this->toJson();
    }
}



class Auth {

    /**
     * @var Project
     */
    private $project;

    public function __construct($project = Null)
    {
        $this->project = is_null($project)? new Project() : $project;
    }

    public function check($user = false){
        if($user == 'user1'){
            $this->project->setName("Project: $user")->setActive(true)->setDescription("This project belongs to $user");
        }
        return $this;
    }

    /**
     * @param Project $project
     *
     * @return Auth
     */
    public function setProject(Project $project): Auth
    {
        $this->project = $project;

        return $this;
    }

    /**
     * @return Project
     */
    public function getProject(): Project
    {
        return $this->project;
    }

}

$auth = new Auth();
echo $auth->check('user1')->getProject();

现在导致:

  

{&#34; name&#34;:&#34; Project:user1&#34;,&#34; active&#34;:true,&#34; description&#34;:&#34;此项目   属于user1&#34;}

但是,您希望在不使用已定义的getter / setter的情况下访问私有字段,就好像它是公共字段一样。因此,我们对Auth类进行一些更改。

class Auth {

    /**
     * @var Project[]
     */
    private $private_project;

    public function __construct($project = Null)
    {
        $this->private_project = is_null($project)? new Project() : $project;
    }

    public function check($user = false){
        if($user == 'user1'){
            $this->private_project->setName("Project: $user")->setActive(true)->setDescription("This project belongs to $user");
        }
        return $this;
    }

    public function __get($name)
    {
        if ($name === 'project'){
            return $this->private_project;
        }
    }

}

现在您可以按照要求流畅地访问该字段:

$auth = new Auth();
echo $auth->check('baduser')->project;
echo  "\n";
echo $auth->check('user1')->project;

结果:

  

{&#34;名称&#34;:&#34;默认&#34;&#34;有源&#34;:假,&#34;描述&#34;:&#34;&#34; }

     

{&#34; name&#34;:&#34; Project:user1&#34;,&#34; active&#34;:true,&#34; description&#34;:&#34;此项目属于user1&#34;}

Laravel的Eloquent模型充分利用__get()函数动态访问模型字段。 Laravel也充分利用__call()魔法来提高流畅度。

我希望这有助于带来一些清晰度。

答案 2 :(得分:1)

如果您不想创建额外的类属性并“保留方法链”,那么yield呢?

class Auth
{
   public function check($user = false)
   {
       $project = false; // make it somehow public

       if($user === 'user1'){
           (yield 'project' => $project); // making it public
       }

       return $this;
   }
}

稍后您可以发现如下:

$array = iterator_to_array($auth->check($user));
// array(1) { ["project"] => bool(false) }

但是要使用,你将无法使用方法链,因为。你需要检索生成器,所以最好修改发现$project的方法。

答案 3 :(得分:0)

您需要将其添加为类变量:

FLAGS_MAX

该属性可按如下方式获得:

class Auth {
   public $project = false;

   public function check($user = false) {
     if($user == 'user1'){
       $this->project = 1;
     }
   }
}

答案 4 :(得分:0)

<?php
class Auth
{
    public $project;
    public function check($user = false)
    {
        $this->project = false;//make it somehow public
        if ($user == 'user1') {
            $this->project = 1;
        }
        return $this;
    }
}

$auth = new Auth();
var_dump($auth->check('user1')->project);

这将返回1.函数中定义的局部变量只是函数内部的accessbile而不是外部因此你需要全局定义它们

答案 5 :(得分:0)

$project是您的案例中的局部变量,在check方法的范围内可见。您可以将其定义为成员:

class Auth {
   public $project = false;
   public function check($user = false){
     if($user == 'user1'){
       $this-project = 1;
     }
   }
}

但是,建议成员public并通过getter访问它,这将检查它是否已初始化,如果没有,则初始化它:

class Auth {
   private $project = false;
   public getProject($user = false) {
      if ($this->project === false) {
          check($user);
      }
      return $this->project;
   }
   public function check($user = false){
     if($user == 'user1'){
       $this-project = 1;
     }
   }
}