<?php
$name = new class('hello world') {
public function __construct(string $name)
{
echo $name;
}
};
<?php
//构造函数的参数。
class User
{
protected $number;
public function __construct()
{
echo "I am parent class constructor";
}
public function getNumber() : float
{
return $this->num;
}
}
//匿名类继承Info类
$number = new class(5) extends User
{
public function __construct(float $num)
{
parent::__construct();
$this->num = $num;
}
};
echo $number->getNumber();
I am parent class constructor5
<?php
interface Info
{
public function __construct(string $name, string $address);
public function getName() : string;
public function getAddress() : string;
}
// 修改后的User类
class User
{
protected $number;
protected $name;
protected $address;
public function __construct()
{
echo "I am parent class constructor";
}
public function getNumber() : float
{
return $this->num;
}
}
$info = new class('revin', 'China') extends User implements Info
{
public function __construct(string $name, string $address)
{
$this->name = $name;
$this->address = $address;
}
public function getName() : string
{
return $this->name;
}
public function getAddress() : string
{
return $this->address;
}
};
echo $info->getName() . ' ' . $info->getAddress();
revin China
class Math
{
public $first_number = 10;
public $second_number = 20;
protected function add() : float
{
return $this->first_number + $this->second_number;
}
public function multiply_sum()
{
return new class() extends Math
{
public function multiply($third_number) : float
{
return $this->add() * $third_number;
}
};
}
}
$math = new Math();
echo $math->multiply_sum()->multiply(2);
60
<?php
class MathTest
{
public $first_number = 20;
public $second_number = 30;
protected function add() : float
{
return $this->first_number + $this->second_number;
}
}
class Math
{
public $first_number = 10;
public $second_number = 20;
protected function add() : float
{
return $this->first_number + $this->second_number;
}
public function multiply_sum()
{
return new class() extends MathTest
{
public function multiply($third_number) : float
{
return $this->add() * $third_number;
}
};
}
}
$math = new Math();
echo $math->multiply_sum()->multiply(2);