-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPropertyAccess.php
More file actions
60 lines (56 loc) · 1.77 KB
/
PropertyAccess.php
File metadata and controls
60 lines (56 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php
namespace Colibri\Base;
/**
* Абстрактный клас простого доступа к private переменным.
*
* Наследуясь от этого класса, вы можете объявлять внутренние переменные
* (private или protected) с первым символом подчёркивания в имени и
* иметь сразу простой public доступ к этим переменным, обращаясь к ним
* без символа подчёркивания. В последствии вы можете некоторые из них
* закрыть на запись и/или чтение перепереопределив методы __get и __set.
*
* <code>
* class CMyClass extends PropertyAccess
* {
* private $_var1;
* }
*
* $x=new CMyClass();
* $x->var1='foobar';
* echo($x->var1);
* </code>
*/
abstract class PropertyAccess
{
/**
* @param string $propName
*
* @return mixed
*
* @throws \RuntimeException
*/
public function __get($propName)
{
$p = '_' . $propName;
if ( ! property_exists($this, $p)) {
throw new \RuntimeException("свойство $p не определено в классе " . static::class);
}
return $this->$p;
}
/**
* @param string $propName
* @param mixed $propValue
*
* @return mixed
*
* @throws \RuntimeException
*/
public function __set($propName, $propValue)
{
$p = '_' . $propName;
if ( ! property_exists($this, $p)) {
throw new \RuntimeException("свойство $p не определено в классе " . static::class);
}
return $this->$p = $propValue;
}
}