Use class functions php

Calling a function within a Class method?

I have been trying to figure out how to go about doing this but I am not quite sure how. Here is an example of what I am trying to do:

class test < public newTest()< function bigTest()< //Big Test Here >function smallTest() < //Small Test Here >> public scoreTest() < //Scoring code here; >> 

Just to make sure: a function and a method is exactly the same function === method. The term method is more often used in OO language to describe the function of a class.

The reason some of the terms are missing is I was on my way out of the office, so I was short on time.

10 Answers 10

class test < public function newTest()< $this->bigTest(); $this->smallTest(); > private function bigTest() < //Big Test Here >private function smallTest() < //Small Test Here >public function scoreTest() < //Scoring code here; >> $testObject = new test(); $testObject->newTest(); $testObject->scoreTest(); 

Is it possible to run a function() from another .php page inside a class function and then grab results inside the class function? e.g I have a query that selects all from a table and then returns a fetch all result set. Is it possible to loop through that result set inside a classes function? e.g class query< public function show()< getResults(); while($stmt->fetchCollumn()) < ECHO RESULTS HERE >

The sample you provided is not valid PHP and has a few issues:

is not a proper function declaration — you need to declare functions with the ‘function’ keyword.

Читайте также:  Os makedirs python 3 примеры

The syntax should rather be:

public function scoreTest()

Second, wrapping the bigTest() and smallTest() functions in public function() <> does not make them private — you should use the private keyword on both of these individually:

class test () < public function newTest()< $this->bigTest(); $this->smallTest(); > private function bigTest() < //Big Test Here >private function smallTest() < //Small Test Here >public function scoreTest() < //Scoring code here; >> 

Also, it is convention to capitalize class names in class declarations (‘Test’).

class test < public newTest()< $this->bigTest(); $this->smallTest(); > private function bigTest() < //Big Test Here >private function smallTest() < //Small Test Here >public scoreTest() < //Scoring code here; >> 

I think you are searching for something like this one.

class test < private $str = NULL; public function newTest()< $this->str .= 'function "newTest" called, '; return $this; > public function bigTest()< return $this->str . ' function "bigTest" called,'; > public function smallTest()< return $this->str . ' function "smallTest" called,'; > public function scoreTest()< return $this->str . ' function "scoreTest" called,'; > > $test = new test; echo $test->newTest()->bigTest(); 

To call any method of an object instantiated from a class (with statement new), you need to «point» to it. From the outside you just use the resource created by the new statement. Inside any object PHP created by new, saves the same resource into the $this variable. So, inside a class you MUST point to the method by $this. In your class, to call smallTest from inside the class, you must tell PHP which of all the objects created by the new statement you want to execute, just write:

Источник

How to call a function or method inside its own class in php?

I declare my class in PHP and several functions inside. I need to call one of this functions inside another function but I got the error that this function is undefined. This is what I have:

4 Answers 4

This is basic OOP. You use the $this keyword to refer to any properties and methods of the class:

I would recommend cleaning up this code and setting the visibility of your methods (e.e. private, protected, and public)

 public function c()< $m = $this->b('Mesage'); echo $m; > > 

You can use class functions using $this

You need to use $this to refer to the current object

$this-> inside of an object, or self:: in a static context (either for or from a static method).

To call functions within the current class you need to use $this , this keyword is used for non-static function members.

Also just a quick tip if the functions being called will only be used within the class set a visibility of private

If you going to call it from outside the class then leave it as it is. If you don’t declare the visibility of a member function in PHP, it is public by default. It is good practice to set the visibility for any member function you write.

Or protected if this class is going to be inherited by another, and you want only the child class to have those functions.

protected function myfunc()<> 

Источник

Use class functions php

Watch out when ‘importing’ variables to a closure’s scope — it’s easy to miss / forget that they are actually being *copied* into the closure’s scope, rather than just being made available.

So you will need to explicitly pass them in by reference if your closure cares about their contents over time:

$one (); // outputs NULL: $result is not in scope
$two (); // outputs int(0): $result was copied
$three (); // outputs int(1)
?>

Another less trivial example with objects (what I actually tripped up on):

//set up variable in advance
$myInstance = null ;

$broken = function() uses ( $myInstance )
if(!empty( $myInstance )) $myInstance -> doSomething ();
>;

//$myInstance might be instantiated, might not be
if( SomeBusinessLogic :: worked () == true )
$myInstance = new myClass ();
>

$broken (); // will never do anything: $myInstance will ALWAYS be null inside this closure.
$working (); // will call doSomething if $myInstance is instantiated

/*
(string) $name Name of the function that you will add to class.
Usage : $Foo->add(function()<>,$name);
This will add a public function in Foo Class.
*/
class Foo
public function add ( $func , $name )
$this -> < $name >= $func ;
>
public function __call ( $func , $arguments ) call_user_func_array ( $this ->< $func >, $arguments );
>
>
$Foo = new Foo ();
$Foo -> add (function() echo «Hello World» ;
>, «helloWorldFunction» );
$Foo -> add (function( $parameterone ) echo $parameterone ;
>, «exampleFunction» );
$Foo -> helloWorldFunction (); /*Output : Hello World*/
$Foo -> exampleFunction ( «Hello PHP» ); /*Output : Hello PHP*/
?>

In case you were wondering (cause i was), anonymous functions can return references just like named functions can. Simply use the & the same way you would for a named function. right after the `function` keyword (and right before the nonexistent name).

$x =& $fn ();
var_dump ( $x , $value ); // ‘int(0)’, ‘int(0)’
++ $x ;
var_dump ( $x , $value ); // ‘int(1)’, ‘int(1)’

Every instance of a lambda has own instance of static variables. This provides for great event handlers, accumulators, etc., etc.

Creating new lambda with function() < . >; expression creates new instance of its static variables. Assigning a lambda to a variable does not create a new instance. A lambda is object of class Closure, and assigning lambdas to variables has the same semantics as assigning object instance to variables.

Example script: $a and $b have separate instances of static variables, thus produce different output. However $b and $c share their instance of static variables — because $c is refers to the same object of class Closure as $b — thus produce the same output.

function generate_lambda () : Closure
# creates new instance of lambda
return function( $v = null ) static $stored ;
if ( $v !== null )
$stored = $v ;
return $stored ;
>;
>

$a = generate_lambda (); # creates new instance of statics
$b = generate_lambda (); # creates new instance of statics
$c = $b ; # uses the same instance of statics as $b

$a ( ‘test AAA’ );
$b ( ‘test BBB’ );
$c ( ‘test CCC’ ); # this overwrites content held by $b, because it refers to the same object

var_dump ([ $a (), $b (), $c () ]);
?>

This test script outputs:
array(3) [0]=>
string(8) «test AAA»
[1]=>
string(8) «test CCC»
[2]=>
string(8) «test CCC»
>

/*
* An example showing how to use closures to implement a Python-like decorator
* pattern.
*
* My goal was that you should be able to decorate a function with any
* other function, then call the decorated function directly:
*
* Define function: $foo = function($a, $b, $c, . ) <. >
* Define decorator: $decorator = function($func) <. >
* Decorate it: $foo = $decorator($foo)
* Call it: $foo($a, $b, $c, . )
*
* This example show an authentication decorator for a service, using a simple
* mock session and mock service.
*/

/*
* Define an example decorator. A decorator function should take the form:
* $decorator = function($func) * return function() use $func) * // Do something, then call the decorated function when needed:
* $args = func_get_args($func);
* call_user_func_array($func, $args);
* // Do something else.
* >;
* >;
*/
$authorise = function( $func ) return function() use ( $func ) if ( $_SESSION [ ‘is_authorised’ ] == true ) $args = func_get_args ( $func );
call_user_func_array ( $func , $args );
>
else echo «Access Denied» ;
>
>;
>;

/*
* Define a function to be decorated, in this example a mock service that
* need to be authorised.
*/
$service = function( $foo ) echo «Service returns: $foo » ;
>;

/*
* Decorate it. Ensure you replace the origin function reference with the
* decorated function; ie just $authorise($service) won’t work, so do
* $service = $authorise($service)
*/
$service = $authorise ( $service );

/*
* Establish mock authorisation, call the service; should get
* ‘Service returns: test 1’.
*/
$_SESSION [ ‘is_authorised’ ] = true ;
$service ( ‘test 1’ );

/*
* Remove mock authorisation, call the service; should get ‘Access Denied’.
*/
$_SESSION [ ‘is_authorised’ ] = false ;
$service ( ‘test 2’ );

Beware of using $this in anonymous functions assigned to a static variable.

class Foo public function bar () static $anonymous = null ;
if ( $anonymous === null ) // Expression is not allowed as static initializer workaround
$anonymous = function () return $this ;
>;
>
return $anonymous ();
>
>

$a = new Foo ();
$b = new Foo ();
var_dump ( $a -> bar () === $a ); // True
var_dump ( $b -> bar () === $a ); // Also true
?>

In a static anonymous function, $this will be the value of whatever object instance that method was called on first.

To get the behaviour you’re probably expecting, you need to pass the $this context into the function.

class Foo public function bar () static $anonymous = null ;
if ( $anonymous === null ) // Expression is not allowed as static initializer workaround
$anonymous = function ( self $thisObj ) return $thisObj ;
>;
>
return $anonymous ( $this );
>
>

$a = new Foo ();
$b = new Foo ();
var_dump ( $a -> bar () === $a ); // True
var_dump ( $b -> bar () === $a ); // False
?>

You can always call protected members using the __call() method — similar to how you hack around this in Ruby using send.

class Fun
<
protected function debug ( $message )
<
echo «DEBUG: $message \n» ;
>

public function yield_something ( $callback )
<
return $callback ( «Soemthing!!» );
>

public function having_fun ()
<
$self =& $this ;
return $this -> yield_something (function( $data ) use (& $self )
<
$self -> debug ( «Doing stuff to the data» );
// do something with $data
$self -> debug ( «Finished doing stuff with the data.» );
>);
>

// Ah-Ha!
public function __call ( $method , $args = array())
<
if( is_callable (array( $this , $method )))
return call_user_func_array (array( $this , $method ), $args );
>
>

$fun = new Fun ();
echo $fun -> having_fun ();

When using anonymous functions as properties in Classes, note that there are three name scopes: one for constants, one for properties and one for methods. That means, you can use the same name for a constant, for a property and for a method at a time.

Since a property can be also an anonymous function as of PHP 5.3.0, an oddity arises when they share the same name, not meaning that there would be any conflict.

Consider the following example:

class MyClass const member = 1 ;

public function member () return «method ‘member'» ;
>

public function __construct () $this -> member = function () return «anonymous function ‘member'» ;
>;
>
>

header ( «Content-Type: text/plain» );

var_dump ( MyClass :: member ); // int(1)
var_dump ( $myObj -> member ); // object(Closure)#2 (0) <>
var_dump ( $myObj -> member ()); // string(15) «method ‘member'»
$myMember = $myObj -> member ;
var_dump ( $myMember ()); // string(27) «anonymous function ‘member'»
?>

That means, regular method invocations work like expected and like before. The anonymous function instead, must be retrieved into a variable first (just like a property) and can only then be invoked.

Источник

Оцените статью