LoginSignup
3
4

More than 5 years have passed since last update.

Swift / PHP でクラスインスタンスのプロパティを取得したい

Last updated at Posted at 2015-09-25

PHP 経験者が Swift 初経験で困ったことシリーズ。

Swift

ver 2.0 で確認。

class ProgrammingLanguage {

    public var name:String = ""
    public var version:String = ""

    init(name: String, version: String) {
        self.name = name
        self.version = version
    }
}

let lang: ProgrammingLanguage = ProgrammingLanguage(name: "Swift", version: "2.0")

for prop in Mirror(reflecting: lang).children {
    print(prop.label!, prop.value)
}

// -> name Swift
// -> version 2.0

インスタンスからアクセスできないプロパティも取得できます。

リファレンスに注意書き書いてあるので、使うつもりの人は用途を踏まえて確認してください。
https://developer.apple.com/library/prerelease/ios/documentation/Swift/Reference/Swift_Mirror_Structure/index.html

PHP

class ProgrammingLanguage {

    public $name = "";
    public $version = "";

    function __construct($name, $version) {
        $this->name = $name;
        $this->version = $version;
    }
}

$lang = new ProgrammingLanguage("PHP", "5.5.27");

$ref = new ReflectionClass($lang);
$props = $ref->getProperties(ReflectionProperty::IS_PUBLIC);

foreach ($props as $prop) {
    echo $prop->getName(), " ", $prop->getValue($lang), PHP_EOL;
}

// -> name PHP
// -> version 5.5.27

取得したいアクセス修飾子は ReflectionClass::getProperties でフィルタリングできます。
また、アクセス修飾子が呼び出し元に依存しても問題ないなら下記で簡単に取得できます。

print_r(get_object_vars($lang));

// -> Array
//    (
//        [name] => PHP
//        [version] => 5.5.27
//    )

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4