这个参数属于这个类的说法有什么意义?

时间:2018-06-05 14:42:44

标签: php oop

当我们发送一个类作为参数时,我们说这个参数属于这个类,如下所示:

const input = {
  ida: true,
  idb: false,
  idc: false,
  ide: true
}

const out = Object.keys(input).reduce((acc, key) => ({...acc, [key]: true}), {});

console.log(out)

但我不明白这个目的,这是一个不是界面的类,为什么我们这样做呢?

2 个答案:

答案 0 :(得分:5)

除了其他原因,这是一种类型提示,它迫使开发人员传递该类的实例而不是其他任何内容:

Class T {
  public function test()
  {
    return 'test';
  }
}

class Y {
  public function test(T $t)
  {
    return $t->test();
  }
}

(new Y())->test('test'); // type error 
(new Y())->test(new T()); // no error

根据文件:

  

类型声明允许函数在调用时要求参数具有某种类型。如果给定值的类型不正确,则会生成错误:在PHP 5中,这将是可恢复的致命错误,而PHP 7将引发TypeError异常。

     

要指定类型声明,应在参数名称前添加类型名称。如果参数的默认值设置为NULL,则可以使声明接受NULL值。

直播示例

Repl - 分别在测试时注释掉。

阅读材料

Type Declaration

Understanding Dependency Injection

答案 1 :(得分:1)

类定义对象的外观。它具有属性(它知道的东西)和方法(它可以做的事情)。例如,名称年龄和身高的人物对象:

gg <- function(x, xlab = deparse(substitute(x)), ylab = NA, freq = FALSE, ...) { 
    x <- round(x)
    ylab <- if(is.na(ylab) & freq) {
        "Frequency" 
    } else if(is.na(ylab) & !freq) {
        "Probability" 
    } else ylab
    z <- if(freq) table(x) else table(x)/length(x)
    plot(z, xlab = xlab, ylab = ylab, ...)
}

# Example of use:
gg(mtcars$gear)    # 'mtcars' is a base R built-in dataset

这个输出是:

<?php

class Person
{
   private $name;
   private $height;
   private $age;

   public function __construct($name, $height, $age)
   {
        $this->name = $name;
        $this->height = $height;
        $this->age = $age;
   }

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

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

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

$bob = new Person('Bob', 6, 50);
$alice = new Person('Alice', 5.4, 22);
$tom = new Person('Tom', 5, 30);

$people = [$bob, $alice, $tom];

foreach ($people as $person) {
    echo 'Hi, I\'m ' . $person->getName() . ', I am ' . $person->getHeight() . 'ft tall and ' . $person->getAge() .' years old.' ."\n";
}

基本上,当您将参数传递给构造函数时,您可以将它们分配给属性,然后使用getter方法访问它们。尝试添加setter方法!

在这里玩https://3v4l.org/v9Wr4

当您将CLASS声明为参数时,如下所示:

Hi, I'm Bob, I am 6ft tall and 50 years old. 
Hi, I'm Alice, I am 5.4ft tall and 22 years old. 
Hi, I'm Tom, I am 5ft tall and 30 years old.

您拒绝接受任何旧变量,而是要求您只能传入DateTime对象。这很简单: - )