クラスの定義とインスタンスの生成

PHP

<?php
class Dog extends Animal {
  // クラスプロパティ
  public static $species = 'Canis lupus familiaris';
  // プロパティ
  public $name;
  public $breed;

  // コンストラクタ
  public function __construct($name, $breed) {
    $this->name = $name;
    $this->breed = $breed;
  }

  // メソッド
  public function bark() {
    echo "Woof!";
  }

  public static function staticMethod() {
    echo "Static method";
  }
}
// インスタンスを作成
$buddy = new Dog("Buddy", "Golden Retriever"); // 引数がないときは()を省略可
$buddy->bark();
echo Dog::$species; // 注意:$が必要!
Dog::staticMethod();

Python

class Dog(Animal):
  # クラス属性
  species = "Canis lupus familiaris"

  # コンストラクタ
  def __init__(self, name, breed):
    self.name = name
    self.breed = breed

  # メソッド
  def bark(self):
    print("Woof!")

  @staticmethod
  def static_method():
    print("Static method")

# インスタンスを作成
buddy = Dog("Buddy", "Golden Retriever") # 関数呼び出し形式でnewを使わない!
buddy.bark()
print(Dog.species) # buddy.bark()もOKだが、同名のインスタンス属性があればそちらが優先される
Dog.static_method()

Javascript

class Dog extends Animal {
  // コンストラクタ
  constructor(name, breed) {
    this.name = name;
    this.breed = breed;
  }

  // メソッド
  bark() {
    console.log("Woof!");
  }

  static staticMethod() {
    console.log("Static method");
  }
}

const buddy = new Dog("Buddy", "Golden Retriever");
buddy.bark()
Dog.staticMethod()

各言語の比較

  • 多重継承: Pythonはclass MyClass (Base1, Base2)のように多重継承をサポート。PHPとJavaScriptはサポートしませんが、PHPにはコード再利用のためのトレイト(trait)という機能があり、またJavaScriptでは代わりにmixinを使います。
  • 属性とメソッドのアクセス権(visibility):PHPではpublicprotectedおよびprivateを指定できます。一方PythonとJavaScriptはアクセスを制限する機能がなく基本的にpublicとなります。かわりにアンダースコアで始まる名前(_name or __name)を使ってprivate属性に対する注意喚起を行います。またPythonの場合、二つのアンダースコアで始まる名前を使う場合name manglingが行われます。
  • 抽象クラスとインタフェース:PHPは両方をサポートします。Pythonは、abcモジュールを使用して抽象クラスを作成し、インタフェースのような機能を提供できます。JavaScript自体には抽象クラスやインタフェースの明確なサポートはありませんが、設計パターンやES6以降のクラス構文を使うことで、これらの概念を模倣することはできます(TypeScriptは両方をサポート)。

その他

Python

  • type(object):オブジェクトのタイプ(クラスオブジェクト)を返します。
  • vars(object):オブジェクトの変数を返します。クラス変数は含まれません。
  • getattr()setattr()delattr()hasattr()

Markdown versions of tables from the attachment:

Table 3-1: Primitive Types and Checking Functions in PHP

Type-Checking Function Type Description
is_bool() Boolean One of the two special values true or false
is_integer() Integer A whole number. Alias of is_int() and is_long()
is_float() Float A floating-point number (a number with a decimal point). Alias of is_double()
is_string() String Character data
is_object() Object An object
is_resource() Resource A handle for identifying and working with external resources such as databases or files
is_array() Array An array
is_null() Null An unassigned value

Table 3-2: Pseudo-type-Checking Functions

Function Description
is_countable() An array or an object that can be passed to the count() function
is_iterable() A traversable data structure—that is, one that can be looped through using foreach
is_callable() Code that can be invoked—often an anonymous function or a function name
is_numeric() Either an int, a long, or a string which can be resolved to a number

Table 3-3: Type Declarations

Type Declaration Since Description
array 5.1 An array. Can default to null or an array
int 7.0 An integer. Can default to null or an integer
float 7.0 A floating-point number (a number with a decimal point). An integer will be accepted—even with strict mode enabled. Can default to null, a float, or an integer
callable 5.4 Callable code (such as an anonymous function). Can default to null
bool 7.0 A Boolean. Can default to null or a Boolean
string 5.0 Character data. Can default to null or a string
self 5.0 A reference to the containing class
[a class type] 5.0 The type of a class or interface. Can default to null
iterable 7.1 Can be traversed with foreach (not necessarily an array—could implement Traversable)
object 7.2 An object
mixed 8.0 Explicit notification that the value can be of any type