/**
  * Exports the PHP code
  *
  * @return string
  */
 public function exportCode()
 {
     $default_properties = $this->_property->getDeclaringClass()->getDefaultProperties();
     $modifiers = \Reflection::getModifierNames($this->_property->getModifiers());
     $default_value = null;
     if (array_key_exists($this->_property->getName(), $default_properties)) {
         $default_value = $default_properties[$this->_property->getName()];
         if (!is_numeric($default_value)) {
             $default_value = "'{$default_value}'";
         }
     }
     return sprintf('%s $%s%s;', join(' ', $modifiers), $this->_property->getName(), !is_null($default_value) ? " = {$default_value}" : '');
 }
Example #2
0
 public function __construct($class, $property, $default = null)
 {
     $property = new \ReflectionProperty($class, $property);
     list($description, $tags) = $this->userguide->parse($property->getDocComment());
     $this->description = $description;
     if ($modifiers = $property->getModifiers()) {
         $this->modifiers = '<small>' . implode(' ', \Reflection::getModifierNames($modifiers)) . '</small> ';
     }
     if (isset($tags['var'])) {
         if (preg_match('/^(\\S*)(?:\\s*(.+?))?$/s', $tags['var'][0], $matches)) {
             $this->type = $matches[1];
             if (isset($matches[2])) {
                 $this->description = $this->markdown->transform($matches[2]);
             }
         }
     }
     $this->property = $property;
     // Show the value of static properties, but only if they are public or we are php 5.3 or
     // higher and can force them to be accessible
     if ($property->isStatic()) {
         $property->setAccessible(true);
         // Don't debug the entire object, just say what kind of object it is
         if (is_object($property->getValue($class))) {
             $this->value = '<pre>object ' . get_class($property->getValue($class)) . '()</pre>';
         } else {
             $this->value = Debug::vars($property->getValue($class));
         }
     }
     // Store the defult property
     $this->default = Debug::vars($default);
 }
Example #3
0
 public function __construct($class, $property)
 {
     $property = new ReflectionProperty($class, $property);
     list($description, $tags) = Kodoc::parse($property->getDocComment());
     $this->description = $description;
     if ($modifiers = $property->getModifiers()) {
         $this->modifiers = '<small>' . implode(' ', Reflection::getModifierNames($modifiers)) . '</small> ';
     }
     if (isset($tags['var'])) {
         if (preg_match('/^(\\S*)(?:\\s*(.+?))?$/', $tags['var'][0], $matches)) {
             $this->type = $matches[1];
             if (isset($matches[2])) {
                 $this->description = Markdown($matches[2]);
             }
         }
     }
     $this->property = $property;
     // Show the value of static properties, but only if they are public or we are php 5.3 or higher and can force them to be accessible
     if ($property->isStatic() and ($property->isPublic() or version_compare(PHP_VERSION, '5.3', '>='))) {
         // Force the property to be accessible
         if (version_compare(PHP_VERSION, '5.3', '>=')) {
             $property->setAccessible(TRUE);
         }
         // Don't debug the entire object, just say what kind of object it is
         if (is_object($property->getValue($class))) {
             $this->value = '<pre>object ' . get_class($property->getValue($class)) . '()</pre>';
         } else {
             $this->value = Kohana::debug($property->getValue($class));
         }
     }
 }
 /**
  * {@inheritdoc}
  * @throws PropertyDefinitionNotFoundException
  */
 public function analyze(DefinitionAnalyzer $analyzer, ClassDefinition $classDefinition, \ReflectionProperty $reflectionProperty)
 {
     $propertyName = $reflectionProperty->getName();
     // Set property metadata
     if ($classDefinition->hasProperty($propertyName)) {
         $classDefinition->getProperty($propertyName)->setIsPublic($reflectionProperty->isPublic())->setModifiers($reflectionProperty->getModifiers());
     }
 }
function reflectProperty($class, $property)
{
    $propInfo = new ReflectionProperty($class, $property);
    echo "**********************************\n";
    echo "Reflecting on property {$class}::{$property}\n\n";
    echo "getModifiers():\n";
    var_dump($propInfo->getModifiers());
    echo "\n**********************************\n";
}
 /**
  * Generic class property resolver.
  *
  * @param \ReflectionProperty $property
  * @param ClassMetadata       $classMetadata
  *
  * @return PropertyMetadata Resolved property metadata
  */
 protected function resolvePropertyMetadata(\ReflectionProperty $property, ClassMetadata $classMetadata) : PropertyMetadata
 {
     // Create method metadata instance
     $propertyMetadata = $classMetadata->propertiesMetadata[$property->getName()] ?? new PropertyMetadata($classMetadata);
     $propertyMetadata->name = $property->getName();
     $propertyMetadata->modifiers = $property->getModifiers();
     $propertyMetadata->isPublic = $property->isPublic();
     $propertyMetadata->typeHint = $this->getCommentTypeHint(is_string($property->getDocComment()) ? $property->getDocComment() : '');
     // Store property metadata to class metadata
     return $classMetadata->propertiesMetadata[$propertyMetadata->name] = $propertyMetadata;
 }
Example #7
0
 public function __construct($class, $property)
 {
     $property = new ReflectionProperty($class, $property);
     list($description, $tags) = self::parse($property->getDocComment());
     $this->data['title'] = $description[0];
     $this->data['description'] = trim(implode("\n", $description));
     if ($modifiers = $property->getModifiers()) {
         $this->data['modifiers'] = implode(' ', Reflection::getModifierNames($modifiers));
     } else {
         $this->data['modifiers'] = 'public';
     }
     if (isset($tags['var'])) {
         if (preg_match('/^(\\S*)(?:\\s*(.+?))?$/', $tags['var'][0], $matches)) {
             $this->data['type'] = $matches[1];
             if (isset($matches[2])) {
                 $this->data['description'] = array($matches[2]);
             }
         }
     }
     $this->data['name'] = $property->name;
     $this->data['class_name'] = $property->class;
     $this->data['is_static'] = $property->isStatic();
     $this->data['is_public'] = $property->isPublic();
     $class_rf = $property->getDeclaringClass();
     if ($property->class != $class) {
         $this->data['is_php_class'] = $class_rf->getStartLine() ? 0 : 1;
     } else {
         $this->data['is_php_class'] = false;
     }
     $have_value = false;
     if ($property->isStatic()) {
         $v = $class_rf->getStaticProperties();
         if (isset($v[$property->name])) {
             $value = $v[$property->name];
             $have_value = true;
         }
     } else {
         if (!$property->isPrivate()) {
             if (!$class_rf->isFinal() && !$class_rf->isAbstract()) {
                 $value = self::getValue($class, $property->name);
                 $have_value = true;
             }
         }
     }
     if ($have_value) {
         $this->data['value'] = self::dump($value);
         $this->data['value_serialized'] = serialize($value);
     }
 }
function reflectProperty($class, $property)
{
    $propInfo = new ReflectionProperty($class, $property);
    echo "**********************************\n";
    echo "Reflecting on property {$class}::{$property}\n\n";
    echo "isDefault():\n";
    var_dump($propInfo->isDefault());
    echo "getModifiers():\n";
    var_dump($propInfo->getModifiers());
    echo "getDeclaringClass():\n";
    var_dump($propInfo->getDeclaringClass());
    echo "getDocComment():\n";
    var_dump($propInfo->getDocComment());
    echo "\n**********************************\n";
}
Example #9
0
function add_class($class_name, $flags)
{
    global $classes, $internal_arginfo;
    $lc = strtolower($class_name);
    $class = new \ReflectionClass($class_name);
    if ($class->isFinal()) {
        $flags |= \ast\flags\CLASS_FINAL;
    }
    if ($class->isAbstract()) {
        $flags |= \ast\flags\CLASS_ABSTRACT;
    }
    $classes[$lc] = ['file' => 'internal', 'conditional' => false, 'flags' => $flags, 'lineno' => 0, 'endLineno' => 0, 'name' => $class_name, 'docComment' => '', 'traits' => []];
    foreach ($class->getDefaultProperties() as $name => $value) {
        $prop = new \ReflectionProperty($class_name, $name);
        $classes[$lc]['properties'][strtolower($name)] = ['flags' => $prop->getModifiers(), 'name' => $name, 'lineno' => 0, 'value' => $value];
    }
    foreach ($class->getConstants() as $name => $value) {
        $classes[$lc]['constants'][strtolower($name)] = ['name' => $name, 'lineno' => 0, 'value' => $value];
    }
    foreach ($class->getMethods() as $method) {
        $meth = new \ReflectionMethod($class_name, $method->name);
        $required = $meth->getNumberOfRequiredParameters();
        $optional = $meth->getNumberOfParameters() - $required;
        $lmname = strtolower($method->name);
        $classes[$lc]['methods'][$lmname] = ['file' => 'internal', 'conditional' => false, 'flags' => $meth->getModifiers(), 'lineno' => 0, 'endLineno' => 0, 'name' => $method->name, 'docComment' => '', 'required' => $required, 'optional' => $optional, 'ret' => null];
        $arginfo = null;
        if (!empty($internal_arginfo["{$class_name}::{$method->name}"])) {
            $arginfo = $internal_arginfo["{$class_name}::{$method->name}"];
            $classes[$lc]['methods'][$lmname]['ret'] = $arginfo[0];
        }
        foreach ($method->getParameters() as $param) {
            $flags = 0;
            if ($param->isPassedByReference()) {
                $flags |= \ast\flags\PARAM_REF;
            }
            if ($param->isVariadic()) {
                $flags |= \ast\flags\PARAM_VARIADIC;
            }
            $classes[$lc]['methods'][strtolower($method->name)]['params'][] = ['file' => 'internal', 'flags' => $flags, 'lineno' => 0, 'name' => $param->name, 'type' => empty($arginfo) ? null : next($arginfo), 'def' => null];
        }
    }
}
Example #10
0
 public function __construct($class, $property)
 {
     $property = new ReflectionProperty($class, $property);
     list($description, $tags) = Docs::parse($property->getDocComment());
     $this->description = $description;
     if ($modifiers = $property->getModifiers()) {
         $this->modifiers = '<small>' . implode(' ', Reflection::getModifierNames($modifiers)) . '</small> ';
     }
     if (isset($tags['var'])) {
         if (preg_match('/^(\\S*)(?:\\s*(.+?))?$/', $tags['var'][0], $matches)) {
             $this->type = $matches[1];
             if (isset($matches[2])) {
                 $this->description = $matches[2];
             }
         }
     }
     $this->property = $property;
     if ($property->isStatic()) {
         $this->value = Docs::debug($property->getValue($class));
     }
 }
 public static function castProperty(\ReflectionProperty $c, array $a, Stub $stub, $isNested)
 {
     $a[Caster::PREFIX_VIRTUAL . 'modifiers'] = implode(' ', \Reflection::getModifierNames($c->getModifiers()));
     self::addExtra($a, $c);
     return $a;
 }
Example #12
0
File: util.php Project: nikic/phan
function add_class($class_name)
{
    global $classes, $internal_arginfo, $internal_classvars;
    $lc = strtolower($class_name);
    $class = new \ReflectionClass($class_name);
    $flags = 0;
    if ($class->isFinal()) {
        $flags = \ast\flags\CLASS_FINAL;
    } else {
        if ($class->isInterface()) {
            $flags = \ast\flags\CLASS_INTERFACE;
        } else {
            if ($class->isTrait()) {
                $flags = \ast\flags\CLASS_TRAIT;
            }
        }
    }
    if ($class->isAbstract()) {
        $flags |= \ast\flags\CLASS_ABSTRACT;
    }
    $classes[$lc] = ['file' => 'internal', 'namespace' => $class->getNamespaceName(), 'conditional' => false, 'flags' => $flags, 'lineno' => 0, 'endLineno' => 0, 'name' => $class_name, 'docComment' => '', 'type' => '', 'traits' => []];
    $parent = $class->getParentClass();
    if (!$parent) {
        $classes[$lc]['parent'] = '';
    } else {
        $classes[$lc]['parent'] = $parent->getName();
    }
    foreach ($class->getDefaultProperties() as $name => $value) {
        $type = $internal_classvars[strtolower($class_name)]['properties'][$name] ?? type_map(gettype($value));
        #		echo "{$class_name}::{$name} = ($type) $value\n";
        $prop = new \ReflectionProperty($class_name, $name);
        $classes[$lc]['properties'][strtolower($name)] = ['flags' => $prop->getModifiers(), 'name' => $name, 'lineno' => 0, 'type' => type_map(gettype($value))];
    }
    $classes[$lc]['interfaces'] = $class->getInterfaceNames();
    $classes[$lc]['traits'] = $class->getTraitNames();
    $parents = [];
    $parent = $class->getParentClass();
    if ($parent) {
        $temp = $class;
        while ($parent = $temp->getParentClass()) {
            $parents[] = $parent->getName();
            $parents = array_merge($parents, $parent->getInterfaceNames());
            $temp = $parent;
        }
    }
    $types = [$class_name];
    $types = array_merge($types, $classes[$lc]['interfaces']);
    $types = array_merge($types, $parents);
    $classes[$lc]['type'] = implode('|', array_unique($types));
    foreach ($class->getConstants() as $name => $value) {
        $classes[$lc]['constants'][$name] = ['name' => $name, 'lineno' => 0, 'type' => type_map(gettype($value))];
    }
    foreach ($class->getMethods() as $method) {
        $meth = new \ReflectionMethod($class_name, $method->name);
        $required = $meth->getNumberOfRequiredParameters();
        $optional = $meth->getNumberOfParameters() - $required;
        $lmname = strtolower($method->name);
        $classes[$lc]['methods'][$lmname] = ['file' => 'internal', 'namespace' => $class->getNamespaceName(), 'conditional' => false, 'flags' => $meth->getModifiers(), 'lineno' => 0, 'endLineno' => 0, 'name' => $method->name, 'docComment' => '', 'required' => $required, 'optional' => $optional, 'ret' => null];
        $arginfo = [];
        unset(${"arginfo1"});
        $alt = 1;
        if (!empty($internal_arginfo["{$class_name}::{$method->name}"])) {
            $arginfo = $internal_arginfo["{$class_name}::{$method->name}"];
            $classes[$lc]['methods'][$lmname]['ret'] = $arginfo[0];
            while (!empty($internal_arginfo["{$class_name}::{$method->name} {$alt}"])) {
                $classes[$lc]['methods']["{$lmname} {$alt}"] = $classes[$lc]['methods'][$lmname];
                ${"arginfo{$alt}"} = $internal_arginfo["{$class_name}::{$method->name} {$alt}"];
                unset(${"arginfo" . ($alt + 1)});
                $classes[$lc]['methods']["{$lmname} {$alt}"]['ret'] = ${"arginfo{$alt}"}[0];
                $alt++;
            }
        } else {
            if (!empty($parents)) {
                foreach ($parents as $parent_name) {
                    if (!empty($internal_arginfo["{$parent_name}::{$method->name}"])) {
                        $classes[$lc]['methods']["{$lmname} {$alt}"] = $classes[$lc]['methods'][$lmname];
                        $arginfo = $internal_arginfo["{$parent_name}::{$method->name}"];
                        $classes[$lc]['methods'][$lmname]['ret'] = $arginfo[0];
                        while (!empty($internal_arginfo["{$parent_name}::{$method->name} {$alt}"])) {
                            ${"arginfo{$alt}"} = $internal_arginfo["{$parent_name}::{$method->name} {$alt}"];
                            unset(${"arginfo" . ($alt + 1)});
                            $classes[$lc]['methods']["{$lmname} {$alt}"]['ret'] = ${"arginfo{$alt}"}[0];
                            $alt++;
                        }
                        break;
                    }
                }
            }
        }
        foreach ($method->getParameters() as $param) {
            $alt = 1;
            $flags = 0;
            if ($param->isPassedByReference()) {
                $flags |= \ast\flags\PARAM_REF;
            }
            if ($param->isVariadic()) {
                $flags |= \ast\flags\PARAM_VARIADIC;
            }
            $classes[$lc]['methods'][strtolower($method->name)]['params'][] = ['file' => 'internal', 'flags' => $flags, 'lineno' => 0, 'name' => $param->name, 'type' => empty($arginfo) ? null : next($arginfo), 'def' => null];
            while (!empty(${"arginfo{$alt}"})) {
                $classes[$lc]['methods'][strtolower($method->name) . ' ' . $alt]['params'][] = ['file' => 'internal', 'flags' => $flags, 'lineno' => 0, 'name' => $param->name, 'type' => empty(${"arginfo{$alt}"}) ? null : next(${"arginfo{$alt}"}), 'def' => null];
                $alt++;
            }
        }
    }
}
Example #13
0
 /**
  * the pretty printer
  * 	I will print all kinds of data in a condensed but nice format
  * 	I will print constants and static properties of objects as well
  * 	I will detect cycle references in objects (but not in arrays)
  * 	I will stop at a certain depth level so array recursion is caught as well
  * @param mixed $param I will print this nicely
  * @param boolean $returnOnly if true, I only return in a string, otherwise I print
  * @param int $indent what I print will be indented this much
  * @param int $maxDepth print no deeper than this but print *DEPTH LIMIT* instead. 0 means no limit
  * @param boolean $isHtml if true I'll do some HTML formatting (<pre> and <b> tags )
  * @param boolean $phpDoc if true, it will look for phpdoc tags of all properties etc
  * @return string|void
  */
 public static function echop($param, $returnOnly = false, $indent = 0, $maxDepth = 9, $isHtml = null, $phpDoc = null)
 {
     static $references = array();
     $str = '';
     $phpDoc = is_null($phpDoc) ? is_null($isHtml) ? !empty($_SERVER['HTTP_HOST']) : ($isHtml ? true : false) : ($phpDoc ? true : false);
     $isHtml = is_null($isHtml) ? !empty($_SERVER['HTTP_HOST']) : ($isHtml ? true : false);
     // if null...
     if (is_null($param)) {
         $str = $isHtml ? '<b>NULL</b>' : 'NULL';
     } elseif (is_object($param)) {
         $hash = spl_object_hash($param);
         // check circular reference
         if (in_array($hash, $references, true)) {
             $str = $isHtml ? '<b>*RECURSION*</b>' : '*RECURSION*';
         } else {
             // push onto reference stack
             $references[] = $hash;
             $className = get_class($param);
             $parentClassName = get_parent_class($param);
             $r = new \ReflectionClass($className);
             // classname
             $str = $className . (empty($parentClassName) ? ' Object' : ' extends ' . $parentClassName) . ' (';
             // depth limit check, by indent
             if ($maxDepth && $maxDepth <= $indent) {
                 $str .= $isHtml ? '<b>*DEPTH LIMIT*</b>)' : '*DEPTH LIMIT*)';
             } else {
                 // constants
                 foreach ($r->getConstants() as $eachConstantName => $eachConstant) {
                     $str .= "\n" . str_repeat("\t", $indent + 1) . 'const [' . ($isHtml ? '<b>' . $eachConstantName . '</b>' : $eachConstantName) . ']' . ' => ' . ($isHtml ? '<b>' . $eachConstant . '</b>' : $eachConstant);
                 }
                 // get an array of static & dynamic property names, statics first
                 $staticPNames = array_keys($r->getStaticProperties());
                 $allPNames = array_map(function ($property) {
                     return $property->name;
                 }, $r->getProperties());
                 $propertyNames = array_merge($staticPNames, array_diff($allPNames, $staticPNames));
                 // print them
                 foreach ($propertyNames as $eachPropertyName) {
                     $p = new ReflectionProperty($className, $eachPropertyName);
                     if ($phpDoc) {
                         $doc = static::_formatPropertyDoc(static::getPropertyDoc($className, $eachPropertyName));
                     }
                     $m = $p->getModifiers();
                     $visiblity = ($m & ReflectionProperty::IS_PRIVATE ? 'private' : '') . ($m & ReflectionProperty::IS_PROTECTED ? 'protected' : '') . ($m & ReflectionProperty::IS_PUBLIC ? 'public' : '');
                     $isStatic = $m & ReflectionProperty::IS_STATIC ? true : false;
                     $p->setAccessible(true);
                     $val = $isStatic ? $p->getValue() : $p->getValue($param);
                     $str .= ($phpDoc ? str_replace("\n", "\n" . str_repeat("\t", $indent + 1), "\n" . $doc) : '') . "\n" . str_repeat("\t", $indent + 1) . ($isStatic ? 'static ' : '') . '[' . ($isHtml ? '<b>' . $eachPropertyName . '</b>' : $eachPropertyName) . ':' . $visiblity . ']' . " => " . static::echop($val, true, $indent + 1, $maxDepth, $isHtml, $phpDoc);
                 }
                 $str .= "\n" . str_repeat("\t", $indent) . ')';
             }
             // pop from reference stack
             array_pop($references);
         }
     } elseif (is_array($param)) {
         // empty arrays should look really compact
         if (empty($param)) {
             $str .= 'Array()';
         } else {
             $str .= 'Array(' . count($param) . ') (';
             // check max depth
             if ($maxDepth && $maxDepth <= $indent) {
                 $str .= ($isHtml ? '<b>*DEPTH LIMIT*</b>' : '*DEPTH LIMIT*') . ')';
             } else {
                 foreach ($param as $eachKey => $eachValue) {
                     $str .= "\n" . str_repeat("\t", $indent + 1) . '[' . $eachKey . "] => " . static::echop($eachValue, true, $indent + 1, $maxDepth, $isHtml, $phpDoc);
                 }
                 $str .= "\n" . str_repeat("\t", $indent) . ')';
             }
         }
     } elseif (is_string($param) || is_numeric($param)) {
         $str = 'string(' . strlen($param) . ') ' . ($isHtml ? '<b>' . $param . '</b>' : $param);
     } elseif (is_bool($param)) {
         $str = 'bool(' . ($param ? $isHtml ? '<b>true</b>' : 'TRUE' : ($isHtml ? '<b>false</b>' : 'FALSE')) . ')';
     } else {
         $str = print_r($param, 1);
     }
     // put in <pre> tags in html mode
     if ($isHtml && !$indent) {
         $str = "\n" . '<pre>' . $str . '</pre>' . "\n";
     }
     // return or print
     if ($returnOnly) {
         return $str;
     }
     echo $str . "\n";
 }
Example #14
0
 /**
  * @param \ReflectionProperty $reflectedProperty
  *
  * @return string
  */
 protected function documentPropertySignature(\ReflectionProperty $reflectedProperty)
 {
     if ($this->processPropertySignature === false) {
         return "";
     }
     $modifiers = implode(' ', \Reflection::getModifierNames($reflectedProperty->getModifiers()));
     $signature = "#### *{$modifiers}* {$reflectedProperty->name}";
     if (is_callable($this->processPropertySignature)) {
         $signature = call_user_func($this->processPropertySignature, $reflectedProperty, $signature);
     }
     return $signature;
 }
 private function getPropertyData(ReflectionProperty $reflectionProperty, &$classData)
 {
     $sclarTypes = array('boolean', 'integer', 'float', 'string', 'array', 'object', 'resource', 'mixed', 'number', 'callback');
     $modifiers = Reflection::getModifierNames($reflectionProperty->getModifiers());
     $docComment = $reflectionProperty->getDocComment();
     if (!$docComment) {
         $docComment = "";
     }
     $parsedComment = $this->parseDocComment($docComment, 'property');
     $type = $parsedComment['var'];
     $out = array();
     $out['type'] = "";
     $out['array_type'] = 0;
     if (preg_match('/\\[\\]$/', $type)) {
         $out['array_type'] = 1;
     }
     if (!$this->isScalar($type) && !empty($type)) {
         if ($type[0] == '\\') {
             $type = substr($type, 1);
         }
         if (preg_match('/\\[\\]$/', $type)) {
             $type = trim($type, "[]");
         }
         $out['type'] = $this->guessClass($type, $classData['namespaces']);
     }
     $out['inheritdoc'] = $parsedComment['inheritdoc'];
     $out['docComment'] = $this->trimDocComment($docComment);
     $origin = $reflectionProperty->getDeclaringClass()->getFileName() == false ? "" : $reflectionProperty->getDeclaringClass()->getFileName();
     $origin = $this->normalizePath($origin);
     $out['origin'] = $origin;
     $classData['properties']['all'][$reflectionProperty->name] = $out;
     foreach ($modifiers as $modifier) {
         $classData['properties']['modifier'][$modifier][] = $reflectionProperty->name;
     }
 }
Example #16
0
 /**
  * @return string[]
  */
 public function getModifieres() : array
 {
     return Reflection::getModifierNames($this->property->getModifiers());
 }
<?php

class String
{
    public $length = 5;
    function accessLengthProp(string $obj, $length)
    {
        $reflection = new ReflectionClass($obj);
        $property = $reflection->getProperty($length);
        $property->setAccessible(true);
        return $property->getValue($obj);
    }
}
$prop = new ReflectionProperty('String', 'length');
printf("<br/>===> The%s%s%s%s property '%s' (which was %s)  having the modifiers %s<br/>", $prop->isPublic() ? ' public' : '', $prop->isPrivate() ? ' private' : '', $prop->isProtected() ? ' protected' : '', $prop->isStatic() ? ' static' : '', $prop->getName(), $prop->isDefault() ? 'declared at compile-time' : 'created at run-time', var_export(Reflection::getModifierNames($prop->getModifiers()), 1));
$obj = new String();
echo "<br/>===> The length property of the object is " . $obj->accessLengthProp($obj, 'length') . "<br/>";
printf("<br/>===> The  value is: ");
echo $prop->getValue($obj) . "<br/>";
$prop->setValue($obj, 10);
printf("<br/>===> The setting value to 10, new value is: ");
echo " " . $prop->getValue($obj);
/* output

===> The public property 'length' (which was declared at compile-time) having the modifiers array ( 0 => 'public', )

===> The length property of the object is 5

===> The value is: 5

===> The setting value to 10, new value is: 10
function getPropertyStr(ReflectionProperty $property, $defaultProperties)
{
    $name = $property->getName();
    $modifiers = Reflection::getModifierNames($property->getModifiers());
    $str = join(' ', $modifiers) . ' $' . $name;
    if (isset($defaultProperties[$name]) && !is_null($defaultProperties[$name])) {
        $str .= ' = ' . var_export($defaultProperties[$name], true);
    }
    return $str . ';';
}
<?php

class C
{
    public static $p;
}
var_dump(new ReflectionProperty());
var_dump(new ReflectionProperty('C::p'));
var_dump(new ReflectionProperty('C', 'p', 'x'));
$rp = new ReflectionProperty('C', 'p');
var_dump($rp->getName(1));
var_dump($rp->isPrivate(1));
var_dump($rp->isProtected(1));
var_dump($rp->isPublic(1));
var_dump($rp->isStatic(1));
var_dump($rp->getModifiers(1));
var_dump($rp->isDefault(1));
Example #20
0
<pre>
<?php 
class String
{
    public $length = 5;
}
// Создание экземпляра класса ReflectionProperty
$prop = new ReflectionProperty('String', 'length');
// Вывод основной информации о свойстве класса
printf("===> %s%s%s%s свойство '%s' (которое было %s)\n" . "     имеет модификаторы %s\n", $prop->isPublic() ? ' public' : '', $prop->isPrivate() ? ' private' : '', $prop->isProtected() ? ' protected' : '', $prop->isStatic() ? ' static' : '', $prop->getName(), $prop->isDefault() ? 'объявлено во время компиляции' : 'создано во время выполнения', var_export(Reflection::getModifierNames($prop->getModifiers()), 1));
exit;
// Создание экземпляра String
$obj = new String();
// Получение текущего значения
printf("---> Значение: ");
var_dump($prop->getValue($obj));
// Изменение значения
$prop->setValue($obj, 10);
printf("---> Установка значения 10, новое значение равно: ");
var_dump($prop->getValue($obj));
// Дамп объекта
var_dump($obj);
?>
</pre>
Example #21
0
 /**
  * Parse a property.
  *
  * @param \ReflectionProperty $property     The reflected property.
  * @param CachedClass         $cachedClass  Object we are building which contains all the data about this class.
  * @param Sources             $sources      Configured sources.
  * @param Conditionals        $conditionals Configured conditionals.
  *
  * @return CachedClass
  *
  * @throws AnnotationException If there is something wrong with the annotations.
  */
 protected function parseProperty(\ReflectionProperty $property, CachedClass $cachedClass, Sources $sources, Conditionals $conditionals) : CachedClass
 {
     $propertyName = $property->getName();
     $declaringClassName = $property->getDeclaringClass()->getName();
     $modifiers = $property->getModifiers();
     $castAs = null;
     $froms = [];
     $annotations = $this->getAnnotationReader()->getPropertyAnnotations($property);
     foreach ($annotations as $anno) {
         if (true === $anno instanceof AsBase) {
             if (null !== $castAs) {
                 throw new AnnotationException('A property can only have zero or one Cast options - ' . $declaringClassName . '::$' . $propertyName . ' has multiple');
             }
             // @todo add validation of cast (especially important for arrays with nested casts)
             $castAs = $anno;
         } elseif (true === $anno instanceof From) {
             /* @var From $anno */
             $anno->sources = $this->validateSources($anno->sources, $declaringClassName . '::$' . $propertyName, $sources);
             $anno->conditions = $this->validateConditions($anno->conditions, $declaringClassName . '::$' . $propertyName, $conditionals);
             $anno->arrayStyles = $this->validateArrayStyles($anno->arrayStyles, $declaringClassName . '::$' . $propertyName);
             if (true === empty($anno->field)) {
                 $anno->field = $propertyName;
             }
             $froms[] = $anno;
         }
         //end if
     }
     //end foreach
     if (false === empty($froms)) {
         /* @var From $from */
         foreach ($froms as $from) {
             $newProperty = new CachedProperty($declaringClassName, $propertyName, $from, $modifiers, $castAs);
             $cachedClass->add($newProperty);
         }
     }
     return $cachedClass;
 }
Example #22
0
 function transformProperty(ReflectionProperty $property, $is_inherited)
 {
     $is_public = $property->isPublic() ? ' public' : '';
     $is_private = $property->isPrivate() ? ' private' : '';
     $is_protected = $property->isProtected() ? ' protected' : '';
     $is_static = $property->isStatic() ? ' static' : '';
     $name = $property->getName();
     $class = $property->getDeclaringClass()->name;
     $modifiers = Reflection::getModifierNames($property->getModifiers());
     extract($this->transformDocBlock($property->getDocComment()));
     ob_start();
     include "templates/" . $this->template . "/property.tmpl.php";
     return ob_get_clean();
 }