Most PHP IDEs rely on phpdoc to get hints about the type of an expression. Yet, I use frequently this pattern, which doesn't seem to be covered:
class Control {
private $label = '';
/** #return ??? */
public static function Make(){ return new static(); }
/** #return ??? */
public function WithLabel($value){ $this->label = $value; return $this; }
/** #return void */
public function Render(){ /* ... */ }
}
class Textbox extends Control {
private $text = '';
/** #return ??? */
public function WithText($text){ $this->width = $text; return $this; }
}
Now I can use the classes like this:
Textbox::Make() // <-- late static binding, returns Textbox
->WithLabel('foo') // <-- late dynamic binding, returns Textbox
->WithText('bar') // <-- normal binding, returns Textbox
->Render();
Is there any way to replace the '???'s with something so that the typing information is correct?
For static methods in classes that may be extended:
/** #return static */
For final-static methods:
/** #return Control */
For non-static methods:
/** #return $this */
but it's not documented in phpdoc manual
Note that nowadays any Intelij IED (like PhpStorm 2019), does support all three static, $this, and self (as return type in PhpDoc).
Updated answer taking as reference the most popular PHP IDE (PHPStorm 8):
For #return you can use:
self
$this
For #method you can use:
$this
Example:
/**
* Class Model
* #method $this parentMethodA
*/
class Model
{
/**
* #return $this
*/
public function parentMethodB()
{
return $this;
}
/**
* #return self
*/
public function parentMethodC()
{
return $this;
}
}
/**
* Class Person
* #method $this childMethodA
*/
class Person extends Model
{
/**
* #return $this
*/
public function childMethodB()
{
return $this;
}
/**
* #return self
*/
public function childMethodC()
{
return $this;
}
}
$p = new Person();
//In the following lines IDE will recognize those variables as:
$t1 = $p->parentMethodA(); //Instance of Person
$t2 = $p->parentMethodB(); //Instance of Person
$t3 = $p->parentMethodC(); //Instance of Model
$t4 = $p->parentMethodA(); //Instance of Person
$t5 = $p->parentMethodB(); //Instance of Person
$t6 = $p->parentMethodC(); //Instance of Person
Update for PHPStorm 10 (EAP)
It seems that now static can be used too, but only for #return.
Updated cvsguimaraes' answer to include static options:
/**
* Class Bar
* #method $this parentMethodA
*/
class Bar
{
/**
* #return $this
*/
public function parentMethodB()
{
return $this;
}
/**
* #return self
*/
public function parentMethodC()
{
return $this;
}
/**
* #return static
*/
public static function staticMethod()
{
return new static();
}
/**
* #param $id
*
* #return bool
*/
public function load($id)
{
// test
return $id ? true : false;
}
/**
* #param null $id
*
* #return static
*/
public static function get($id = NULL){
$obj = static::staticMethod();
if (is_null($id)) {
return $obj;
}
if ($obj->load($id)) {
return $obj;
}
return false;
}
}
/**
* Class Foo
* #method $this childMethodA
*/
class Foo extends Bar
{
/**
* #return $this
*/
public function childMethodB()
{
return $this;
}
/**
* #return self
*/
public function childMethodC()
{
return $this;
}
}
/**
* Class Bar
*/
class Baz extends Bar
{
}
$p = new Foo();
/** #var Foo $Foo */
$Foo = 'Foo';
$Baz = 'Bar';
// IntelliJ recognizes the following as:
$t1 = $p->parentMethodA(); //Instance of Foo
$t2 = $p->parentMethodB(); //Instance of Foo
$t3 = $p->parentMethodC(); //Instance of Model
$t4 = $p->childMethodA(); //Instance of Foo
$t5 = $p->childMethodB(); //Instance of Foo
$t6 = $p->childMethodC(); //Instance of Foo
$t7 = $Foo::staticMethod(); //Instance of Foo
$t8 = Foo::staticMethod(); //Instance of Foo
$t9 = $p::staticMethod(); //Instance of Foo
$t10 = $Foo::get(); //Instance of Foo
$t12 = Bar::get(); //Instance of Bar
$t11 = $Baz::get(); // Unknown
Related
i wrote a sample test case for collection like class but weird thing about this is in my testAdd method that i add a item in CustomCollectionService and it changed my parameter too. how can this happend?
class CustomCollectionService
{
/**
* #var Collection $collection
*/
public $collection;
public function makeCollection($arr)
{
$this->collection = collect($arr);
}
/**
* #param Collection $collection
*/
public function setCollection(Collection $collection): void
{
$this->collection = $collection;
}
/**
* #return mixed
*/
public function getCollection()
{
return $this->collection;
}
public function add($item)
{
return $this->collection->add($item);
}
}
and this is my test:
class CustomCollectionTest extends TestCase
{
public $collectionService;
public $collection;
protected function setUp(): void
{
$this->collectionService = new CustomCollectionService();
}
public function testCollectionCreator()
{
$arr = ['sina','1',5];
$this->assertIsArray($arr);
return $arr;
}
/**
* #param $arr
* #depends testCollectionCreator
*/
public function testAction($arr)
{
$this->collectionService->makeCollection($arr);
$this->assertIsArray($this->collectionService->getCollection()->toArray());
return $this->collectionService->getCollection();
}
/**
* #depends testAction
*/
public function testAdd($col)
{
$actualCount = $col->count();
$this->collectionService->setCollection($col);
$manipulatedCollection = $this->collectionService->add(['xx']);
dump($actualCount); // 3
dump($col->count()); //4
$this->assertEquals($actualCount+1, $manipulatedCollection->count());
}
}
Because it is an object. So when you pass the $col object to the CollectionService and call the add method within the CollectionService, it is still the $col object from your test method that is being used.
I'm using a builder pattern to create an object, call methods, and return back to the calling object.
class Caller{
public function invoke() {
new Builder($this)->setColor('red')->setSize(5)-> // need typehint for Caller to return here
}
public function next() {
}
}
class Builder{
/**
* #var ????
*/
private $caller;
/**
* #param ???? $caller
*/
public function __construct($caller) {
$this->caller = $caller;
}
public function setColor($color) {
$this->color = $color;
return $this;
}
/**
* #param int $size
* #return ????
*/
public function setSize($size) {
$this->size = $size;
return $this->caller;
}
}
There is a way to invoke a parent method and return the child typehints by specifying $this as the return type in the parent class, but how can I reference a separate class type stored in $this->caller as the return type and get the typehints?
I'm creating a small API, mostly for learning purposes, but, I might implement it into a project I'm working on. So far, I have installed the zend expressive skeleton application and set up my models and entities. I'm able to query the database and get results, but, when I return the results as a JSON Response, I can only see a list of empty arrays for each result. I would like to be able to return the actual objects that are being returned from the database instead of converting them to arrays.
HomePageHandler.php
<?php
declare(strict_types=1);
namespace App\Handler;
use App\Entity\Product;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Zend\Diactoros\Response\HtmlResponse;
use Zend\Diactoros\Response\JsonResponse;
use Zend\Expressive\Router;
use Zend\Expressive\Template\TemplateRendererInterface;
use App\Model\ProductModel;
class HomePageHandler implements RequestHandlerInterface
{
/** #var string */
private $containerName;
/** #var Router\RouterInterface */
private $router;
/** #var null|TemplateRendererInterface */
private $template;
private $productModel;
public function __construct(
string $containerName,
Router\RouterInterface $router,
?TemplateRendererInterface $template = null,
ProductModel $productModel
) {
$this->containerName = $containerName;
$this->router = $router;
$this->template = $template;
$this->productModel = $productModel;
}
public function handle(ServerRequestInterface $request) : ResponseInterface
{
$data = $this->productModel->fetchAllProducts();
return new JsonResponse([$data]);
//return new HtmlResponse($this->template->render('app::home-page', $data));
}
}
I'm expecting a JSON Response returned with a list of 18 "Product" entities. My results look like.
[[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]]
Let me know if there is any other code you would like to see.
Thanks in advance!
Edited with Product.php code
<?php
/**
* Created by PhpStorm.
* User: Brock H. Caldwell
* Date: 3/14/2019
* Time: 4:04 PM
*/
namespace App\Entity;
class Product
{
protected $id;
protected $picture;
protected $shortDescription;
protected $longDescription;
protected $dimensions;
protected $price;
protected $sold;
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
/**
* #param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* #return mixed
*/
public function getPicture()
{
return $this->picture;
}
/**
* #param mixed $picture
*/
public function setPicture($picture)
{
$this->picture = $picture;
}
/**
* #return mixed
*/
public function getShortDescription()
{
return $this->shortDescription;
}
/**
* #param mixed $shortDescription
*/
public function setShortDescription($shortDescription)
{
$this->shortDescription = $shortDescription;
}
/**
* #return mixed
*/
public function getLongDescription()
{
return $this->longDescription;
}
/**
* #param mixed $longDescription
*/
public function setLongDescription($longDescription)
{
$this->longDescription = $longDescription;
}
/**
* #return mixed
*/
public function getDimensions()
{
return $this->dimensions;
}
/**
* #param mixed $dimensions
*/
public function setDimensions($dimensions)
{
$this->dimensions = $dimensions;
}
/**
* #return mixed
*/
public function getPrice()
{
return $this->price;
}
/**
* #param mixed $price
*/
public function setPrice($price)
{
$this->price = $price;
}
/**
* #return mixed
*/
public function getSold()
{
return $this->sold;
}
/**
* #param mixed $sold
*/
public function setSold($sold)
{
$this->sold = $sold;
}
public function exchangeArray($data)
{
$this->id = (!empty($data['id'])) ? $data['id'] : null;
$this->picture = (!empty($data['picture'])) ? $data['picture'] : null;
$this->shortDescription = (!empty($data['shortDescription'])) ? $data['shortDescription'] : null;
$this->longDescription = (!empty($data['longDescription'])) ? $data['longDescription'] : null;
$this->dimensions = (!empty($data['dimensions'])) ? $data['dimensions'] : null;
$this->price = (!empty($data['price'])) ? $data['price'] : null;
$this->sold = (!empty($data['sold'])) ? $data['sold'] : null;
}
}
You need to either make the properties public, or implement the JsonSerializable interface in your Product entity. All of its properties are protected, which is fine, but that means they aren't exposed when the object is JSON encoded.
Here are some brief examples:
class Example1 { protected $a = 1; }
class Example2 { public $b = 2; }
class Example3 implements JsonSerializable {
protected $c = 3;
public function jsonSerialize() {
return ['c' => $this->c];
}
}
echo json_encode([new Example1, new Example2, new Example3]);
The result:
[{},{"b":2},{"c":3}]
If you choose to implement JsonSerializable, exactly how you do it is up to you, but you just need a jsonSerialize() method that returns the properties you want in the JSON result in a format accessible to json_encode (an object with public properties or an array).
This question already has answers here:
PHP class instance to JSON
(5 answers)
Closed 4 years ago.
I got an object. I need to turn into JSON for storage but when I try to encode it into JSON it returns an empty JSON object. When I tried to use json_last_error.
The code I used
echo $payload["sub"];
echo json_encode($user);
echo json_last_error_msg();
The result I get
"102573480781696194937{}No error".
The User class I'm trying to encode
<?php
/**
* Created by PhpStorm.
* User: Student
* Date: 13-4-2018
* Time: 10:40
*/
namespace php;
class User
{
private $isAdmin = false;
private $registeredFood = array();
private $googleID;
private $name;
private $notes = array();
private $email;
/**
* User constructor.
* #param $googleID
*/
public function __construct($googleID)
{
$this->googleID = $googleID;
}
/**
* #return mixed
*/
public function getGoogleID()
{
return $this->googleID;
}
/**
* #return bool
*/
public function isAdmin()
{
return $this->isAdmin;
}
/**
* #param bool $isAdmin
*/
public function setIsAdmin($isAdmin)
{
$this->isAdmin = $isAdmin;
}
/**
* #return array
*/
public function getRegisteredFood()
{
return $this->registeredFood;
}
/**
* #param array $registeredFood
*/
public function setRegisteredFood($registeredFood)
{
$this->registeredFood = $registeredFood;
}
/**
* #return mixed
*/
public function getName()
{
return $this->name;
}
/**
* #param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* #return array
*/
public function getNotes()
{
return $this->notes;
}
/**
* #param array $notes
*/
public function setNotes($notes)
{
$this->notes = $notes;
}
/**
* #return mixed
*/
public function getEmail()
{
return $this->email;
}
/**
* #param mixed $email
*/
public function setEmail($email)
{
$this->email = $email;
}
}
?>
I hope someone can help me
It is because your class's properties are private.
An example class with only private properties ...
php > class Foo { private $bar = 42; }
php > $obj = new Foo();
do not expose values:
php > echo json_encode($obj);
{}
But an example class with public properties ...
php > class Bar { public $foo = 42; }
php > $objBar = new Bar();
do it!
php > echo json_encode($objBar);
{"foo":42}
\JsonSerializable
PHP provide an'interafce \JsonSerializable that require a method jsonSerialize. This method is automatically called by json_encode().
class JsonClass implements JsonSerialize {
private $bar;
public function __construct($bar) {
$this->bar = $bar;
}
public function jsonSerialize() {
return [
'foo' => $this->bar,
];
}
}
I prefer this solution because is not good to expose publicly properties
serialization and unserialization ...
If you need to serialize and unserialize php object you can ...
php > class Classe { public $pub = "bar"; }
php > $obj = new Classe();
php > $serialized = serialize($obj);
php > $original = unserialize($serialized);
php > var_dump($original);
php shell code:1:
class Classe#2 (1) {
public $pub =>
string(3) "bar"
}
$serialized variable contains O:6:"Classe":1:{s:3:"pub";s:3:"bar";}. As you can see is not a json, but is a format that allow you to recreate original object using unserialize function.
You have a couple of options here.
Option 1: Make your class properties public
Like what sensorario mentioned, change the visibility of your properties so that it is accessible from outside the class, which is where you are calling json_encode.
Option 2: Introduce a method/function within the class to return the encoded JSON object
Have a toJson() function inside your User class.
Of course, there are way more options - such as extending User so that User is not "contaminated", etc.
But yup, the general problem is your private properties.
I'm using Netbeans 6.9 and writing a PHP class that implements the Iterator interface. I would like to have the IDE offer Intellisense as I iterate over the items in my object. It seems to work for the Zend Framework as I've noticed that when iterating over a Zend_Db_Rowset I get intellisense for a Zend_DB_Row. For example, when I write:
foreach($rowset as $row) {
$row->delete();
}
When I type "$row->" Netbeans pops up its code hints for the member functions of Zend_Db_Row_Abstract. Unfortunately, I can't get this to work for my own code. Below is a sample I tried to get to work:
class Foo {
private $value;
/**
*
* #param string $value
*/
public function setValue($value) {
$this->value = $value;
}
/**
*
* #return string
*/
public function getValue() {
return $this->value;
}
}
class It implements Iterator {
private $data;
public function __construct($data) {
$this->data = $data;
}
/**
*
* #return Foo
*/
public function current() {
return current($this->data);
}
/**
*
* #return Foo
*/
public function key() {
return key($this->data);
}
/**
*
* #return Foo
*/
public function next() {
return next($this->data);
}
/**
*
* #return Foo
*/
public function rewind() {
return reset($this->data);
}
/**
*
* #return bool
*/
public function valid() {
return key($this->data) !== null;
}
}
$a = new Foo();
$b = new Foo();
$a->setValue('Hello');
$b->setValue('Bye');
$testData = array($a, $b);
$myIt = new It($testData);
foreach ($myIt as $obj) {
echo $obj->getValue();
}
Strangely the intellisense seems to think $obj is an object of type It when I want it to think (and it actually is) an object of type Foo.
Within the body of the loop you can provide the type hint in a comment.
/* #var $obj Foo */
+1 for Brian Fisher's suggestion.