This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP method chaining?
In a lot of APIs I've worked with, I've seen this sort of thing:
$object->method()->anotherMethod();
From the tutorials on OOP that I've read, this is how classes are written,
<?php
class myClass {
public method() {
// do something
}
}
?>
When should this be used, and how can it be done? Apologies, but I am new to OOP.
If your method returns $this, you will be able to use the above style ($object->method()->anotherMethod()). This can be done only in cases where your method is not expected to return something else, e.g. a method named like getSomething() is expected to return Something, but if you have a method that has no relevant value to return, you can just return $this, allowing method call chains.
This is called Method Call Chaining. There are no hard and fast rules about when you should use it, but the general rule I use is that method chaining makes sense when there are a series of object methods that are frequently called one after the other, such as initialization functions.
Related
This question already has answers here:
What is ::class in PHP?
(4 answers)
Closed 2 years ago.
Actually I don't have idea what is difference in both methods
Laravel Official documentation uses this below method for declaring relationship
class User extends Model
{
public function phone()
{
return $this->hasOne('App\Phone'); // HERE (App\Phone) Parameter
}
}
and most of the tutorials and experts (even in Laracon's) uses this below method.
class User extends Model
{
public function phone()
{
return $this->hasOne(Phone::class); // HERE (Phone::class) Parameter
}
}
In short what is difference in both, And which is convenient.
return $this->hasOne(Phone::class); // Method one
/// VS
return $this->hasOne('App\Phone'); // Method Two
Since PHP 5.5 the class keyword is used for class name resolution. This means it returns the fully qualified ClassName. This is extremely useful when you have namespaces, because the namespace is part of the returned name.
Using the ::class keyword is the way to go. First because you write less, and second, using this your IDE can help you find the class faster.
But they're basically the same thing.
You can find more about that here
They are both the same but Phone::class is new syntax
let's assume you want to move your Phone class to another folder you have to find every 'App\Phone' and rename it to New\Directory\Phone but when you use Phone::class you don't have to worry about that.
This question already has answers here:
Check variable is public php
(3 answers)
Closed 7 years ago.
I'm building a class. I intend for this class to be a sort of master parent class for a lot of API and database interactions later on.
Assume it looks something like this
class api_controller{
public $method = 'get';
private $table;
protected $table_id_column;
//Rest of code is really not needed
}
I was wondering if it was possible, from within PHP, to figure out if a variable is public,private, or protected if given the name? If it is, I had planned to use it as a checking station to make sure that no child methods alter data they've been restricted from accessing via an inherited method.
I had googled my question and came up with a lot of get_object_vars() vs get_class_vars() discussions, as well as a great many discussions about the difference between private, protected, and public. From my search of Object/Class functions through the PHP database, I didn't see anything that immediately jumped out at me as my answer.
I was thinking that it may have to be a try/catch statement done by accessing the variable and seeing if it throws an error (which would let me know if it was public/private), but I'm unsure of how to determine past that point. Even then, this method would have to be a member of the parent class, so it would have access to all of its own private variables.
Any Ideas?
Use Reflection:
$class = new ReflectionClass('api_controller');
$property = $class->getProperty('method');
// then you could check by
// there are also methods of isProtected, isPublic, etc...
if ($property->isPrivate()) {
// ..
}
This question already has answers here:
PHP: Static and non Static functions and Objects
(5 answers)
Closed 8 years ago.
I am still learning OOP PHP and I keep swapping and changing between the following way of calling methods within an object
$obj = new Model();
$obj->method($param);
against
Model::method($params);
I understand the difference when I within the method as I can use $this in the first example, and I have to use self:: in the second.
Which is the correct way and what are the reasons of using each way
The reason I ask is I cannot find a suitable search term to research. I am currently reading a book on OOP and it will probably tell at some point, but would be nice to know now.
Foo::bar() calls the static class method, while $foo->bar() calls the instance method on an object. These are two completely different things. You do not need an object instance to call Foo::bar(), and in fact you do not have access to instance data when doing so. Foo::bar() is essentially nothing else but a regular function call like bar(), except that the function is attached to a class.
Instance methods act on a specific object instance:
class User {
protected $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public static function hi() {
// no access to $this->name here, since static
// methods are not bound to specific instances
echo 'Hi';
}
}
$dave = new User('Dave');
$mary = new User('Mary');
echo $dave->getName(); // Dave
echo $mary->getName(); // Mary
User::hi(); // Hi
Unless you understand this, you know nothing about OOP.
First example is a non-static call to the method, second a static call.
The first is better if you want to access private variables of your Model, second is better if you use the method like a normal function.
In general you should declare methods of the first type as static (public static function method(){}).
First case is invocation of method on class instance, second case is call of static method.
See http://php.net/manual/en/language.oop5.static.php
There is no "proper" way because both call types serve different purposes.
The first call type is the standard way of handling objects: You initialize a concrete instance of a class. This instance can have its own internal values and each instance can use these values to create a different result when you call the method with the same parameter.
The second call type is called static and operates directly on the class, there is no instance (hence no $this). There are some use cases for it, see this answer for Java, it's the same for PHP.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP: How to chain method on a newly created object?
I can create an instance and call it's method via:
$newObj = new ClassName();
$newObj -> someMethod();
But is there any way I can do it in a shorter notation, an anonymous instance? I tried this:
(new ClassName())->someMethod();
But it doesn't seem to work as expected.
Additional Info: The method I want to call is public but not static.
PHP 5.4 supports it.
If you can't update you can workaround like this:
function yourclass($param) {
return new yourclass($param);
}
yourclass()->method();
Don't forget that your constructor must return $this;
Not that i know of.
But! - You could implement a Singleton Pattern and then call:
ClassName::getInstance()->someMethod();
Or, to cut it short ;)
ClassName::gI()->someMethod();
If someMethod does not refer to $this, you could also simply call it as a static function, though it wasn't defined as one:
ClassName::someMethod();
If the method is static and doesn't rely on any class variables (maybe you've put it in a class just for organisation purposes), you can simply call it staticly as phil is demonstrating with getInstance:
ClassName::someMethod()
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
In PHP, can you instantiate an object and call a method on the same line?
Is it possible?
Normally, it requires two lines:
$instance = new MyClass();
$variable = $instance->method();
Is something like this possible in PHP?:
$variable = new MyClass()->method();
Of course, the first code is better for readability and clean code, etc., but I was just curious if you can shrink it. Maybe it could be useful, if the method returned another instance, e.g.:
$instance = new MyClass()->methodThatReturnsInstance();
Is it possible in PHP?
Previously answered:
In PHP, can you instantiate an object and call a method on the same line?
You could make a static method that constructs a default instance and return it.
class Foo
{
public static function instance() { return new Foo(); }
...
}
echo Foo::instance()->someMethod();
I don't really recommend this though as it's just syntactic sugar. You're only cutting out one line and losing readability.
The feature you have asked for is available from PHP 5.4. Here is the list of new features in PHP 5.4:
http://docs.php.net/manual/en/migration54.new-features.php
And the relevant part from the new features list:
Class member access on instantiation has been added, e.g. (new Foo)->bar().