Are there "magic functions" for powershell objects? - powershell

In PHP, there are "magic methods" that exist if you need them to. An example of this is the __toString() method which is used to echo out a specific string if a piece of code attempts to echo the object. This is an example using PHP:
<?php
// Declare a simple class
class TestClass
{
public $foo;
public function __construct($foo)
{
$this->foo = $foo;
}
public function __toString()
{
return $this->foo;
}
}
$class = new TestClass('Hello');
echo $class;
?>
Which would return:
Hello
Is there a "magic function" that will do this in Powershell?

All default PSObjects in PowerShell have a ToString() method, and if you're creating your custom objects in script (and not code), then you are going to have this method already present. All you need to to is override the ToString() method using Add-Member.
Please see this question for an exact description of this.
You can see what members your custom object has by piping an instance of the object to Get-Member.

Related

What is the common term for both class and object?

All OOP languages support having a variable refer to an object. But some languages also support having a variable refer to a class (class-reference type). Say I have a method that will accept either an object or a class as its parameter. What would I call the parameter? In other words, is there a term that both encapsulates "object" and "class"?
To further clarify, here's some (otherwise useless) PHP code that illustrates what I mean by class reference vs object reference:
<?php
class Foo {
public function shout(string $message) {
echo strtoupper("$message\n");
}
}
class Bar {
public function shout(string $message) {
echo "!!! $message !!!\n";
}
}
/**
* #param mixed $classOrObject
*/
function shoutOut($classOrObject) {
if (is_object($classOrObject)) {
$classOrObject->shout('I got an object');
} elseif (is_string($classOrObject)) {
$object = new $classOrObject();
$object->shout('I got a class');
}
}
shoutOut(new Foo());
shoutOut(Bar::class);
A rephrase of the question can hence be
What is a better name for the $classOrObject parameter?
As a third attempt at homing in on what I'm really after here, imagine you're writing an introduction to OOP. You could say something like
The main ingredients of the OOP paradigm are the class and object.
So if we were to substitute "main ingredients" with a more theoretically accurate term, my question is what would that term be? If classes were apples and objects were pears, we'd call them both "fruit". But classes and objects are not fruit, so what do we call them?
An object is instance of class.
A class is like mold and the object is an element created with this mold.

How to use instance of class in same class Perl

I'm new to OOPerl, and wanted to know how I can reference an instance of a class within that class (i.e. $this in PHP) so that I'm able to call its "private" methods
To make it more clear:
in PHP for instance:
class Foo {
public function __construct(){
}
public function doThis(){
$that = $this->doThat(); //How to reference a "private" function in perl that is defined in the same class as the calling function?
return $that;
}
private function doThat(){
return "Hi";
}
}
Perl methods are ordinary subroutines that expect the first element of their parameter array #_ to be the object on which the method is called.
An object defined as
my $object = Class->new
can then be used to call a method, like this
$object->method('p1', 'p2')
The customary name is $self, and within the method you assign it as an ordinary variable, like this
sub method {
my $self = shift;
my ($p1, $p2) = #_;
# Do stuff with $self according to $p1 and $p2
}
Because the shift removes the object from #_, all that is left are the explicit parameters to the method call, which are copied to the local parameter variables.
There are ways to make inaccessible private methods in Perl, but the vast majority of code simply trusts the calling code to do the right thing.

PHP: Echo variable name of an object?

I want to echo the name of the variable object i'm calling, in this case controller_01.
I'm using get_class, but it wont print the variable name, only the object type :(
<?php
class remoteControl{
private $chip = "Intel64<br />";
public function openCase(){
echo "The controler has a " .get_class($this);
return $this->chip;
}
}
$control_01 = new remoteControl();
echo $control_01-> openCase();
?>
You can't do that just like that. An object can have multiple references, but the object isn't itself aware of those references.
The only thing you could do, is to enumerate through every variable you can find and check if it points to the object. But those references could exists also in arrays, or in properties of other objects.
And your design is really flawed if you need the object to find its reference variables this way.

How to use Zend Framework's Partial Loop with Objects

I am quite confused how to use partialLoop
Currently I use
foreach ($childrenTodos as $childTodo) {
echo $this->partial('todos/_row.phtml', array('todo' => $childTodo));
}
$childrenTodos is a Doctrine\ORM\PersistantCollection, $childTodo is a Application\Models\Todo
I tried doing
echo $this->partialLoop('todos/_row.phtml', $childrenTodos)
->setObjectKey('Application\Models\Todo');
But in the partial when I try to access properties/functions of my Todo class, I cant seem to get them always ending up with either call to undefined method Zend_View::myFunction() when I use $this->myFunction() in the partial or if I try $this->todo->getName() I get "Call to a member function getName() on a non-object". How do I use partialLoops?
Try this
echo $this->partialLoop('todos/_row.phtml', $childrenTodos)
->setObjectKey('object');
Then in your partial you can access the object like this
$this->object
object is the name of the variable that an object will be assigned to
You can also do this once in your Bootstrap or other initialization class if you have access to the view object like so
protected function initPartialLoopObject()
{
$this->_view->partialLoop()->setObjectKey('object');
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
$viewRenderer->setView($this->_view);
}
I also had "Call to function on non object" error when trying suggested syntax, seems like they've changed something on later versions of Zend Framework. The following works for me on ZF1.12:
echo $this->partialLoop()
->setObjectKey('object')
->partialLoop('todos/_row.phtml', $childrenTodos);

Wordpress: Accessing A Plugin's Function From A Theme

I'm trying to add some functionality from a plugin I have made into a Wordpress theme but I am having little joy. The documentation doesn't really help me solve the problem so perhaps someone here can help.
I have a plugin in Wordpress that is activated and working fine. The class for this plugin has a function called generateHtml which I would like to access from a Wordpress Theme. But whatever I try, I cannot seem to access my plugin's code.
Can either give me a summary of what I need to do to get a theme accessing code from a plugin and/or point out there I am going wrong in my code:
Plugin:
<?php
/** Usual comments here **/
if (!class_exists("ImageRotator")) {
class ImageRotator {
private $uploadPath = '';
private $pluginPath = '';
private $options;
function __construct() {
$this->uploadPath = dirname(__file__).'\\uploads\\';
// add_shortcode('imagerotator', array(&$this, 'generateHtml'));
}
// Various functions for plugin
function generateHtml() {
echo '<p>Hello World</p>';
}
}
}
/**
* Create instance of image rotator
*/
$imageRotator = new ImageRotator();
/**
* Create actions & filters for Wordpress
*/
if (isset($imageRotator)) {
// Actions
add_action('admin_menu', array(&$imageRotator, 'createMenu'));
add_action('admin_init', array(&$imageRotator, 'registerSettings'));
add_action('imagerotator_show', array(&$imageRotator, 'generateHtml'));
}
Portion from theme header page:
<?php if (isset($imageRotator)) {
$imageRotator->generateHtml();
} else if (isset($ImageRotator)) {
print_r($ImageRotator);
} else {
echo '<p>Nope!</p>';
}
if (function_exists("imagerotator_show")) {
echo 'Function found';
} else {
echo 'Function NOT found';
}
?>
Currently all I ever see is "Nope" and "Function NOT found". Thanks for any input.
Lee,
For starters, "imagerotator_show" is not a function; it's the name of a type of action. When you use the add_action() function, Wordpress just adds your method to the list of functions/methods to call when a particular action is triggered. Thus your second test will always respond with 'Function NOT found'.
The most likely cause of the first problem is failing to declare the method you want to call as a public method. You're also making the code harder than it needs to be.
The best practice I've seen for declaring methods and registering hooks from a class looks something like this:
if ( ! class_exists( 'Foo' ) ):
class Foo {
function __construct() {
add_action( 'hook_name', array( &$this, 'my_hook_implementation' ) );
}
function my_hook_implementation() {
// does something
}
public function my_special_method() {
// does something else
}
}
if ( class_exists( 'Foo' ) ):
$MyFoo = new Foo();
This allows your class to keep all of its implementation details private. When you need to call my_special_method(), you do it as follows:
$MyFoo->my_special_method();
#andrew since I can't comment I thought I would answer your ancillary question. See:
http://net.tutsplus.com/tutorials/wordpress/create-wordpress-plugins-with-oop-techniques/
Where it is explained that when defining a callback function from an object you have to use the array function. It's basically saying get the function 'my_hook_implementation' from the object $this and use it as the callback parameter to the add action hook. It is because you defined the function within the scope of the object and you have to define the scope in order for PHP to know what function you are talking about. The scope being the object referred to by the variable $this.
You just need to use do_action() function, inside your theme.
If you want the function generateHtml to appears inside your header.php you just need to open the header.php file and paste <?php do_action('imagerotator_show'); ?> where you want and then your function will be called there.