Assign value directly in php constructor with a external function - php

Can I assign to a property a value in the constructor, without define any parameter, using for instance an external function?
Example
function my_external_function() {
return 'Good Morning World';
}
class MyClass {
protected $_my_property;
public function __construct() {
$this->_my_property = my_external_function() != '' ? my_external_function() : 'Good night World!';
}
public function getOtherMethod() {
return $this->_my_property;
}
}
$obj = new MyClass();
echo $obj->getOtherMethod();

You can do this. The code in your question will work, but there is a problem with this approach.
If you write your class this way, it will always depend on that external function, but it will have no control over whether or not it even exists, let alone whether or not it will return a value the constructor can use. If you move, rename, or modify the external function, it could change the behavior of your class in unpredictable ways.
I would recommend something like this instead, which I think may accomplish what you're trying to accomplish (not sure) without forcing your class to blindly depend on an external function.
class MyClass {
protected $_my_property = 'Good night World!'; // set a default value here
public function __construct($x = null) { // give your constructor an optional argument
if ($x) { // use the optional argument if it's provided
$this->_my_property = $x;
}
}
public function getOtherMethod() {
return $this->_my_property;
}
}
You can still create an instance of your class with no argument
$obj = new MyClass();
and when you call $obj->getOtherMethod(); you'll get the default value.
You can still use the external function; just let it pass its value into your object's constructor instead of using it within the constructor.
$obj = new MyClass(my_external_function());

Yes, but you better avoid such tricky dependencies.

Related

Access a class within a function

Using as an example the class defined here
class Testclass {
private $testvar = "default value";
public function setTestvar($testvar) {
$this->testvar = $testvar;
}
public function getTestvar() {
return $this->testvar;
}
function dosomething()
{
echo $this->getTestvar();
}
}
$Testclass = new Testclass();
$Testclass->setTestvar("another value");
$Testclass->dosomething();
I would like to add inside a function "one more value", like this:
function test_function() {
$Testclass->setTestvar("one more value");
}
But it doesn´t work. I gives the error message undefined variable Testclass. In order to make it work, I have to define the variable as global within the function, like this:
function test_function() {
global Testclass;
$Testclass->setTestvar("one more value");
}
I am quite new to PHP, but it seems rather strange to me this way of using it. From the main PHP file it´s already defined, but when I use it from a function I have to define again.Basically what I am trying to do is to create a class that creates a new file and adds strings to it from different functions. Is there not a better way? Any suggestions? Many thanks in advance.
One way is to use singleton
MyClass::getInstance()->doSomethingUsefull();
Sometimes you can use static method
MyClass::doIt();
Functions have their own private variable scope. So (for example) you can use $i in a function without worrying about it screwing up another $i somewhere else in the program. If you want to have a function perform actions on an already-existing object, just pass the object as a parameter to the function:
function test_function(Testclass $testclass)
{
$testclass->setTestvar("one more value");
}
Then call it with your object:
$Testclass = new Testclass();
test_function($Testclass);
Note: If the functions you're defining outside the class are tightly related to the class, then you probably want to define them as methods inside the class instead of separate stand-alone functions.

Storing a reference to a class function in a variable in PHP

Here is a hypothetical example (the parent class PageState, contains an instance of the class FooterState - the instance may not be created, depending on the conditions. The FooterState needs to call a function which is public and is created in the PageState class):
class PageState {
private $footer_state = null;
function PageState() {
$this->footer_state= new FooterState($this);
}
public function getExpectedPageDimensions() {
// do calculations based on existing body content
return $dimensions;
}
}
class FooterState {
private $get_dimensions_func = null;
function FooterState($page_state) {
// Here, we need to get the reference to the function from the $page_state class
$this->get_dimensions_func = $page_state->getExpectedPageDimensions;
}
public function addLogos($logo_data) {
$page_dimensions = $this->get_dimensions_func();
// use the page dimensions to decide on the size of the content
return Array('width' => $width, 'height' => $height);
}
I am aware of alternative solutions:
Instead of making a copy of the reference to the function, create a refference to the class $this->page_state = $page_state; and then functions in FooterState can call $this->page_state->getExpectedPageDimensions();
Use global $PageStateInstance; and then just call $PageStateInstance->getExpectedPageDimensions();
But I am wondering if it is at all possible to store a reference to a class function in a variable. If the functions were outside of the class, it would be possible to do stuff like $func = 'getExpectedPageDimensions'; $func();.
You can pass on an instance plus a function as a callable: An array with the instance and the function name. There is a similar system for calling static class methods.
# An example callback method
class MyClass {
function myCallbackMethod() {
echo 'Hello World!';
}
}
# create an instance
$obj = new MyClass();
# and later:
call_user_func(array($obj, 'myCallbackMethod'));
From the docs here: http://php.net/manual/en/language.types.callable.php
Instead of making a copy of the reference to the function, create a refference to the class $this->page_state = $page_state; and then functions in FooterState can call $this->page_state->getExpectedPageDimensions();
This is the best generic solution.
But I am wondering if it is at all possible to store a reference to a class function in a variable.
Yes it is, but it really only works for static functions unless you instantiate the class. Example:
class A {
public static function doSomethingStatic() {
// ...
}
public function doSomethingElse() {
// ...
}
}
$somevar = 'A::doSomethingStatic';
$result = call_user_func($somevar); // calls A::doSomethingStatic();
$myA = new A();
$myref = array($myA, 'doSomethingElse');
$result = call_user_func($myref); // calls $myref->doSomethingElse();
Note that in the second example you have to instantiate the class and pass an array as the first parameter to call_user_func().
References: http://php.net/manual/en/function.call-user-func.php and http://php.net/manual/en/language.types.callable.php
is at all possible to store a reference to a class function
I think you mean object instead of class, but yes you can, with closures.
I don't think you need to though. $this->page_state seems like it'll work just fine.
Don't use globals.

How to Pass a function to a class in php

I have a class that generates data based on a few things. I would like to format that data from the outside. So I am trying to pass a function into the class so that it would format that data. I have looked at many examples, but it seems this is unique.
Can anybody give an idea of how to do this? The following code gives an error.
<?php
class someClass {
var $outsideFunc; // placeholder for function to be defined from outside
var $somevar='Me'; // generated text
function echoarg($abc){
$outsideFunc=$this->outsideFunc; // bring the outside function in
call_user_func($outsideFunc,$abc); // execute outside function on text
echo $abc;
}
}
function outsidefunc($param){ // define custom function
$param='I am '.$param;
}
$someClass=new someClass();
$someClass -> outsideFunc = 'outsideFunc'; // send custom function into Class
$someClass -> echoarg($someClass->somevar);
$someClass -> outsidefunc = 'outsidefunc';
In PHP, function names are not case sensitive, yet object property names are. You need $someClass->outsideFunc, not $someClass->outsidefunc.
Note that good OOP design practice calls for the use of getter and setter methods rather than just accessing properties directly from outside code. Also note that PHP 5.3 introduced support for anonymous functions.
Yeah. You are right. Now there is no error. But it does not work either.
By default, PHP does not pass arguments by reference; outsidefunc() does not actually do anything useful. If you want it to set $param in the caller to something else, and do not want to just return the new value, you could change the function signature to look like this:
function outsidefunc(&$param) {
You would also need to change the way you call the function, as call_user_func() does not allow you to pass arguments by reference. Either of these ways should work:
$outsideFunc($abc);
call_user_func_array($outsideFunc, array(&$abc));
Why not pass your function as an argument?
<?php
class someClass {
public $somevar="Me";
public function echoarg($abc,$cb=null) {
if( $cb) $cb($abc);
echo $abc;
}
}
$someClass = new someClass();
$someClass->echoarg($someClass->somevar,function(&$a) {$a = "I am ".$a;});
i am not sure what exactly you are looking for, but what i get is, you want to pass object in a function which can be acheive by
Type Hinting in PHP.
class MyClass {
public $var = 'Hello World';
}
function myFunction(MyClass $foo) {
echo $foo->var;
}
$myclass = new MyClass;
myFunction($myclass);
OP, perhaps closures are what you're looking for?
It doesn't do EXACTLY what you're looking for (actually add function to class), but can be added to a class variable and executed like any normal anonymous function.
$myClass->addFunc(function($arg) { return 'test: ' . $arg });
$myClass->execFunc(0);
class myClass {
protected $funcs;
public function addFunc(closure $func) {
$this->funcs[] = $func;
}
public function execFunc($index) { $this->funcs[$index](); } // obviously, do some checking here first.
}

Assigning a function's result to a variable within a PHP class? OOP Weirdness

I know you can assign a function's return value to a variable and use it, like this:
function standardModel()
{
return "Higgs Boson";
}
$nextBigThing = standardModel();
echo $nextBigThing;
So someone please tell me why the following doesn't work? Or is it just not implemented yet? Am I missing something?
class standardModel
{
private function nextBigThing()
{
return "Higgs Boson";
}
public $nextBigThing = $this->nextBigThing();
}
$standardModel = new standardModel;
echo $standardModel->nextBigThing; // get var, not the function directly
I know I could do this:
class standardModel
{
// Public instead of private
public function nextBigThing()
{
return "Higgs Boson";
}
}
$standardModel = new standardModel;
echo $standardModel->nextBigThing(); // Call to the function itself
But in my project's case, all of the information stored in the class are predefined public vars, except one of them, which needs to compute the value at runtime.
I want it consistent so I nor any other developer using this project has to remember that one value has to be function call rather then a var call.
But don't worry about my project, I'm mainly just wondering why the inconsistency within PHP's interpreter?
Obviously, the examples are made up to simplify things. Please don't question "why" I need to put said function in the class. I don't need a lesson on proper OOP and this is just a proof of concept. Thanks!
public $nextBigThing = $this->nextBigThing();
You can only initialize class members with constant values. I.e. you can't use functions or any sort of expression at this point. Furthermore, the class isn't even fully loaded at this point, so even if it was allowed you probably couldn't call its own functions on itself while it's still being constructed.
Do this:
class standardModel {
public $nextBigThing = null;
public function __construct() {
$this->nextBigThing = $this->nextBigThing();
}
private function nextBigThing() {
return "Higgs Boson";
}
}
You can't assign default values to properties like that unless that value is of a constant data type (such as string, int...etc). Anything that essentially processes code (such as a function, even $_SESSION values) can't be assigned as a default value to a property. What you can do though is assign the property whatever value you want inside of a constructor.
class test {
private $test_priv_prop;
public function __construct(){
$this->test_priv_prop = $this->test_method();
}
public function test_method(){
return "some value";
}
}
class standardModel
{
// Public instead of private
public function nextBigThing()
{
return "Higgs Boson";
}
}
$standardModel = new standardModel(); // corection
echo $standardModel->nextBigThing();

PHP access external $var from within a class function

In PHP, how do you use an external $var for use within a function in a class? For example, say $some_external_var sets to true and you have something like
class myclass {
bla ....
bla ....
function myfunction() {
if (isset($some_external_var)) do something ...
}
}
$some_external_var =true;
$obj = new myclass();
$obj->myfunction();
Thanks
You'll need to use the global keyword inside your function, to make your external variable visible to that function.
For instance :
$my_var_2 = 'glop';
function test_2()
{
global $my_var_2;
var_dump($my_var_2); // string 'glop' (length=4)
}
test_2();
You could also use the $GLOBALS array, which is always visible, even inside functions.
But it is generally not considered a good practice to use global variables: your classes should not depend on some kind of external stuff that might or might not be there !
A better way would be to pass the variables you need as parameters, either to the methods themselves, or to the constructor of the class...
Global $some_external_var;
function myfunction() {
Global $some_external_var;
if (!empty($some_external_var)) do something ...
}
}
But because Global automatically sets it, check if it isn't empty.
that's bad software design. In order for a class to function, it needs to be provided with data. So, pass that external var into your class, otherwise you're creating unnecessary dependencies.
Why don't you just pass this variable during __construct() and make what the object does during construction conditional on the truth value of that variable?
Use Setters and Getters or maybe a centralized config like:
function config()
{
static $data;
if(!isset($data))
{
$data = new stdClass();
}
return $data;
}
class myClass
{
public function myFunction()
{
echo "config()->myConfigVar: " . config()->myConfigVar;
}
}
and the use it:
config()->myConfigVar = "Hello world";
$myClass = new myClass();
$myClass->myFunction();
http://www.evanbot.com/article/universally-accessible-data-php/24

Categories