Answer the question
In order to leave comments, you need to log in
How to make "magic" methods in PHP?
It is necessary to make it possible to call the properties of the class through "magic" methods (for example, like calling the properties of models in Magento)
Example:
the MyClass class has an awesome_data property, you need to make a "magic" method to call this property: setting this property: MyClass::setAwesomeData()
How can this be done?
pS: a class can have any number of properties and they can be called differently, but methods should not be written for them manually.
ppS: the best example is calling data from a model in Magento
Answer the question
In order to leave comments, you need to log in
What you need...
class MyClass
{
public function __call($method = null, $data = null)
{
$parts = preg_split('/([A-Z][^A-Z]*)/', $method, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$type = array_shift($parts);
if ($type != 'get' && $type != 'set') {
return;
}
$varName = strtolower(implode('_', $parts));
switch ($type) {
case 'set' :
$this->$varName = $data;
break;
case 'get':
return isset($this->$varName) ? $this->$varName : null;
break;
}
return;
}
}
And what's the problem?
You have obviously already heard about magical methods.
<?php
class MyClass {
private
$data = array();
public function __construct() {
$this->data = array(
'test' => 'data test',
'test2' => 'data test 2'
);
}
public function __call( $method = null, $data = null ){
$type = strtolower( substr( $method, 0, 2 ) );
switch( type ) {
case 'set': {
$this->data[strtolower( substr( $method, 3 ) )] = $data;
break;
}
case 'get': {
$key = strtolower( substr( $method, 3 ) );
return isset( $this->data[$key] ) ? $this->data[$key] : null;
break;
}
}
return null;
}
}
$object = new MyClass();
print $object->getTest(); // data test
print $object->getTest2(); // data test 2
$object->setFoo( 'bar' );
print $object->getFoo(); // bar
print $object->getFoo2(); // null
class Test {
static $data = array();
public static function __callStatic($name, $params) {
$propName = substr($name, 3);
if (substr($name, 0, 3) == "set") {
return static::$data[$propName] = $params[0];
}
return static::$data[$propName];
}
}
Test::setMyName("Bob");
Test::getMyName(); //Bob
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question