Skip to content
This repository was archived by the owner on Apr 24, 2021. It is now read-only.

Commit dcc2673

Browse files
committed
some update
1 parent adfe9c7 commit dcc2673

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

example/property_exists.php

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
/**
3+
* Created by PhpStorm.
4+
* User: Inhere
5+
* Date: 2018/5/6 0006
6+
* Time: 12:45
7+
*/
8+
9+
class Some {
10+
public $prop0;
11+
private $prop1;
12+
protected $prop2;
13+
14+
/**
15+
* @return mixed
16+
*/
17+
public function getProp1()
18+
{
19+
return $this->prop1;
20+
}
21+
}
22+
23+
24+
echo "use class:\n";
25+
26+
echo 'public: ' . (property_exists(Some::class, 'prop0') ? 'Y':'N') . PHP_EOL;
27+
echo 'private: ' . (property_exists(Some::class, 'prop1') ? 'Y':'N') . PHP_EOL;
28+
echo 'protected: ' . (property_exists(Some::class, 'prop2') ? 'Y':'N') . PHP_EOL;
29+
30+
echo "use object:\n";
31+
32+
$object = new Some();
33+
34+
echo 'public: ' . (property_exists($object, 'prop0') ? 'Y':'N') . PHP_EOL;
35+
echo 'private: ' . (property_exists($object, 'prop1') ? 'Y':'N') . PHP_EOL;
36+
echo 'protected: ' . (property_exists($object, 'prop2') ? 'Y':'N') . PHP_EOL;

src/PhpHelper.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,34 @@ public static function callByArray(callable $cb, array $args)
6363
return self::call($cb, ...$args);
6464
}
6565

66+
/**
67+
* 给对象设置属性值
68+
* - 会先尝试用 setter 方法设置属性
69+
* - 再尝试直接设置属性
70+
* @param mixed $object An object instance
71+
* @param array $options
72+
* @return mixed
73+
*/
74+
public static function initObject($object, array $options)
75+
{
76+
foreach ($options as $property => $value) {
77+
if (\is_numeric($property)) {
78+
continue;
79+
}
80+
81+
$setter = 'set' . \ucfirst($property);
82+
83+
// has setter
84+
if (\method_exists($object, $setter)) {
85+
$object->$setter($value);
86+
} elseif (\property_exists($object, $property)) {
87+
$object->$property = $value;
88+
}
89+
}
90+
91+
return $object;
92+
}
93+
6694
/**
6795
* 获取资源消耗
6896
* @param int $startTime

0 commit comments

Comments
 (0)