Измените класс игры в кости на это.
public class Dice {
private Random random;
public Dice(){
random = new Random();
}
public int throwDice(){
int dice = random.nextInt(6) + 1;
return dice;
}
}
И обновить roll = dice.throwDice();
внутри цикла. Это будет работать, потому что ваша игральная кость теперь имеет один случайный экземпляр, который генерирует новые случайные целые числа каждый раз, когда вызывается throwDice()
.
class Animal {
var $name;
function __construct($name) {
$this->name = $name;
}
}
class Dog extends Animal {
function speak() {
return "Woof, woof!";
}
}
class Cat extends Animal {
function speak() {
return "Meow...";
}
}
$animals = array(new Dog('Skip'), new Cat('Snowball'));
foreach($animals as $animal) {
print $animal->name . " says: " . $animal->speak() . '<br>';
}
You can label it all you want, but that looks like polymorphism to me.
, хотя PHP не поддерживает перегрузку методов по сравнению с другими языками, скажем, Java. но вы можете иметь перегрузку метода в PHP, но метод определения отличается. если вы хотите иметь разные функциональные возможности для данного метода с другим набором параметров в PHP, вы можете сделать что-то вроде этого:
class myClass {
public function overloadedMethod() {
// func_num_args() is a build-in function that returns an Integer.
// the number of parameters passed to the method.
if ( func_num_args() > 1 ) {
$param1 = func_get_arg(0);
$param2 = func_get_arg(1);
$this->_overloadedMethodImplementation2($param1,$param2)
} else {
$param1 = func_get_arg(0);
$this->_overloadedMethodImplementation1($param1)
}
}
protected function _overloadedMethodImplementation1($param1) {
// code 1
}
protected function _overloadedMethodImplementation2($param1,$param2) {
// code 2
}
}
может быть более чистая реализация, но это всего лишь пример.
PHP поддерживает наследование и интерфейсы. так что вы можете иметь полиморфизм, используя их. у вас может быть такой интерфейс:
// file: MyBackupInterface.php
interface MyBackupInterface {
// saves the data on a reliable storage
public function saveData();
public function setData();
}
// file: myBackupAbstract.php
require_once 'MyBackupInterface.php';
class MyBackupAbstract implements MyBackupInterface {
protected $_data;
public function setData($data) {
$this->_data= $data;
}
// there is no abstract modifier in PHP. so le'ts avoid this class to be used in other ways
public function __construct() {
throw new Exception('this class is abstract. you can not instantiate it');
}
}
// file: BackupToDisk.php
require_once 'MyBackupAbstract.php';
class BackupToDisk extends MyBackupAbstract {
protected $_savePath;
// implement other methods ...
public function saveData() {
// file_put_contents() is a built-in function to save a string into a file.
file_put_contents($this->_savePath, $this->_data);
}
}
// file: BackupToWebService.php
require_once 'MyBackupAbstract.php';
class BackupToWebService extends MyBackupAbstract {
protected $_webService;
// implement other methods ...
public function saveData() {
// suppose sendData() is implemented in the class
$this->sendData($this->_data);
}
}
теперь в вашем приложении, вы можете использовать его следующим образом:
// file: saveMyData.php
// some code to populate $myData
$backupSolutions = array( new BackupToDisk('/tmp/backup') , new BackupToWebService('webserviceURL') );
foreach ( $backupSolutions as $bs ) {
$bs->setData($myData);
$bs->saveData();
}
вы правы, PHP не является строго типизированным языком, мы никогда не упоминали, что любой из ваших $ backupSolutions будет ' MyBackupAbstract 'или' MyBackupInterface ', но это не помешает нам иметь природу полиморфизма, которая отличается функциональностью по сравнению с использованием тех же методов.
__call()
and __callStatic()
should support method overloading. More on this is available in the manual. Or what exactly are you after?
UPDATE: I just noticed the other replies.
For another way to overload a method, consider the following:
<?php
public function foo()
{
$args = func_get_arg();
}
Certainly not pretty, but it allows you to do virtually whatever you want.
You can still override methods, just not overload them. Overloading (in C++) is where you use the same method name for multiple methods, differing only in number and types of parameters. This would be hard in PHP since it's weak-typed.
Overriding is where the sub-class replaces a method in the base class. Which is really the basis for polymorphism, and you can do that in PHP.