How do I convert my functions to a class?

时间:2017-08-30 20:17:43

标签: php oop

I am trying to get into the world of OOP and therefore building my first class out of some file handler functions. I am having a hard time understanding the whole idea of objects and methods, and I am not quite sure if I did it the right way, though the output is as expected.

I would appreciate your help with the following example. How could I add a method to it the right way?

class.File.php

data.frame

example call

library(tidyverse)
library(broom)

melt_testdata %>% 
  group_by(variable) %>% 
  do(glance(t.test(value ~ W, data = .)))

1 个答案:

答案 0 :(得分:2)

对象是现实世界的具体实体。这有属性和行为(方法)。

具体文件的属性是什么?这是一个名称,权限,创建日期等。所有属性都应该隐藏在现实世界中。

该文件有什么行为?阅读内容,重写内容,附加内容,重命名,删除,更改权限等。您对文件所做的一切。注意,最好有两个方法“重写内容”和“追加内容”,而不是一个带有参数的“put”。因为这些是对文件的不同操作。

所以让我们写一个文件类。

class File
{
    private $name;
    private $permissions;

    // name and permissions are mandatory because file cannot exist without these properties
    public function __construct($name, $permissions)
    {
        $this->name = $name;
        $this->permissions = $permissions;
    }

    public function read()
    {
        // you can check if the file exists
        return file_get_contents($this->name);
    }

    // may also named `put`
    public function write($content)
    {
        file_put_contents($this->name, $content);
    }

    public function append($content)
    {
        file_put_contents($this->name, $content, FILE_APPEND);
    }

    public function rename($name)
    {
        $this->name = $name;
    }
}

任何检查(如果文件存在,如果文件是可写的)是具体实现,而不是关于OOP。

PS 您可以阅读本文http://www.yegor256.com/2014/09/16/getters-and-setters-are-evil.html有关getter和setter的信息。