You can avoid using (new ...)->
by using a static method, which creates the new
instance internally.
Combining this with the magic __toString
method allows you to directly echo the created instance.
Here is how to write it:
<?php
class Post_Share {
/**
* Using Post_Share::generate() will directly return the new instance,
* so (new Post_Share) is not needed.
*/
public static function generate( $networks = array(), $post, $style, $display = 'no' ) {
return new self( $networks, $post, $style, $display );
}
/**
* Calling additional methods can be avoided by echoing the instance.
*/
public function __toString() {
// Backup
$original_display = $this->display_it;
$this->display_it = false;
// Generate
$output = $this->generate_share_links();
// Restore
$this->display_it = $original_display;
return $output;
}
// ...your own code
}
Once you do it this way, you can do both of these:
<?php Post_Share::generate( array( 'facebook' ), $post, 'share-style-2' )->generate_share_links() ?>
and
<?php echo Post_Share::generate( array( 'facebook' ), $post, 'share-style-2' ) ?>
There are a few things happening here:
- The
static
keyword in the first method means that you do not need to create an instance of the class in order to call the method, you just call the class name, followed by double colons and then the method name (ex.Post_share::generate
). - The
self
keyword refers to the name of the current class.new self
is equal tonew Post_Share
. - By using the static method, you can avoid having to wrap the class instantiation with brackets, so no
(new ...)
. - The
__toString
method is called automatically once PHP attempts to transform the class to a string. This happens when echoing the class (like in the example), concatenating it (`Post_Share::generate(…) . ‘ more text’) and etc.