Run code on creation of a PHP class instance? - php

I want code to run whenever I create a new object. For example, see this:
<?php
class Test {
echo 'Hello, World!';
}
$test = new Test;
?>
I want it to echo "Hello, World!" whenever I create a new instance of this object, without calling a function afterward. Is this possible?

You should read about constructor
<?php
class MyClass {
public function __construct() {
echo "This code is executed when class in instanciated.";
}
}
?>

class Test {
function __construct(){
echo 'Hello, World!';
}
}

Or on PHP 4 use:
class Test {
function Test {
echo 'Hi';
}
}
Edit: This also works on PHP 5, so this is the best way to do it.

Related

PHP use class function on sub-functions

i have test class with one function , after including that i can use this class function with included pages but i cant use this function on included page's functions, for example:
testClass.php:
class test
{
public function alert_test( $message )
{
return $message;
}
}
including class:
in this using class i dont have problem
text.php:
<?php
include 'testClass.php';
$t= new test;
echo alert_test('HELLO WORLD');
?>
but i cant use alert_test function with this method:
<?php
include 'testClass.php';
$t= new test;
function test1 ( $message )
{
echo alert_test('HELLO WORLD');
/*
OR
echo $t->alert_test('HELLO WORLD');
*/
}
?>
i want to use test class in sub-functions
What about echo $t->alert_test('HELLO WORLD');? You have to 'tell' PHP where he has to find that function, in this case in $t which is an instance of the test class.
<?php
include 'testClass.php';
function test1 ( $message )
{
$t = new test;
echo $t->alert_test('HELLO WORLD');
}
?>
You should pass the instance ($t) to your function, i.e:
<?php
class test
{
public function alert_test( $message )
{
return $message;
}
}
$t = new test;
function test1 ( $message, $t )
{
echo $t->alert_test('HELLO WORLD');
}
As an alternative (better IMHO) you could declare your function as static, so that you don't even need to instantiate the test class, i.e:
class Message {
static function alert($message) {
echo $message;
}
}
function test_alert($msg) {
Message::alert($msg);
}
test_alert('hello world');
You should "have problem" even in your first example, because alert_test() is an instance function of your test class.
You have to invoke instance methods as:
$instance -> method( $params );
So:
$t -> alert_test();
But local functions [as your test1] should not rely on global objects: pass them as a function argument, if you need.
You can use closures:
$t = new test;
function test1($message) use ($t) {
$t->test_alert($message);
}

Setting Up PHP Class's without a framework

Does anyone have a guide or can provide me with a quick example how to set up a class and pass the data from the class to the index.php?
I was thinking I could do it like I do in a framework can I not?
$this->class->function();
coolclass.php
class coolClass
{
public function getPrintables()
{
return "hello world!";
}
}
index.php
include 'coolclass.php';
$instance = new coolClass();
echo $instance->getPrintables();
A quick example:
Foo.php
class Foo {
public __construct() {
..initialize your variables here...
}
public function doSomething() {
..have your function do something...
}
}
Index.php:
Include('Foo.php');
$my_Foo = Foo();
$my_Foo->doSomething();
I think its fairly straight-forward as to what's happening here...so ill leave it at that. Don't want to give too much away.

calling methods in object oriented php

I'm sure this will look like stupid question for most of you. However, I've been banging my head for quite a while over it.
Coming from ASP.NET/C#, I'm trying to use PHP now. But the whole OOrintation gives me hard time.
I have the following code:
<html>
<head>
</head>
<body>
<?php
echo "hello<br/>";
class clsA
{
function a_func()
{
echo "a_func() executed <br/>";
}
}
abstract class clsB
{
protected $A;
function clsB()
{
$A = new clsA();
echo "clsB constructor ended<br/>";
}
}
class clsC extends clsB
{
function try_this()
{
echo "entered try_this() function <br/>";
$this->A->a_func();
}
}
$c = new clsC();
$c->try_this();
echo "end successfuly<br/>";
?>
</body>
</html>
To my simple understanding this code should result with the following lines:
hello
clsB constructor ended
entered try_this() function
a_func() executed
however, it does not run 'a_func', all I get is:
hello
clsB constructor ended
entered try_this() function
Can anyone spot the problem?
Thanks in advanced.
Your problem lies here:
$A = new clsA();
Here, you're assigning a new clsA object to the local variable $A. What you meant to do was assign it to the property $A:
$this->A = new clsA();
As the first answer but also you could extend the b class to the a class this way you can access the a class in C, like below:
<?php
echo "hello<br/>";
class clsA{
function a_func(){
echo "a_func() executed <br/>";
}
}
abstract class clsB extends clsA{
function clsB(){
echo "clsB constructor ended<br/>";
}
}
class clsC extends clsB{
function try_this(){
echo "entered try_this() function <br/>";
self::a_func();
}
}
$c = new clsC();
$c->try_this();
echo "end successfuly<br/>";
?>

How do you execute a method in a class from the command line

Basically I have a PHP class that that I want to test from the commandline and run a certain method. I am sure this is a basic question, but I am missing something from the docs. I know how to run a file, obviously php -f but not sure how to run that file which is a class and execute a given method
This will work:
php -r 'include "MyClass.php"; MyClass::foo();'
But I don't see any reasons do to that besides testing though.
I would probably use call_user_func to avoid harcoding class or method names.
Input should probably use some kinf of validation, though...
<?php
class MyClass
{
public function Sum($a, $b)
{
$sum = $a+$b;
echo "Sum($a, $b) = $sum";
}
}
// position [0] is the script's file name
array_shift(&$argv);
$className = array_shift(&$argv);
$funcName = array_shift(&$argv);
echo "Calling '$className::$funcName'...\n";
call_user_func_array(array($className, $funcName), $argv);
?>
Result:
E:\>php testClass.php MyClass Sum 2 3
Calling 'MyClass::Sum'...
Sum(2, 3) = 5
Here's a neater example of Repox's code. This will only run de method when called from the commandline.
<?php
class MyClass
{
public function hello()
{
return "world";
}
}
// Only run this when executed on the commandline
if (php_sapi_name() == 'cli') {
$obj = new MyClass();
echo $obj->hello();
}
?>
As Pekka already mentioned, you need to write a script that handles the execution of the specific method and then run it from your commandline.
test.php:
<?php
class MyClass
{
public function hello()
{
return "world";
}
}
$obj = new MyClass();
echo $obj->hello();
?>
And in your commandline
php -f test.php

PHP syntax: constructing a class from a member variable

I am trying to make a class from a member variable like this:
<?
class A{
private $to_construct = 'B';
function make_class(){
// code to make class goes here
}
}
class B{
function __construct(){
echo 'class constructed';
}
}
$myA = new A();
$myA->make_class();
?>
I tried using:
$myClass = new $this->to_construct();
and
$myClass = new {$this->to_construct}();
but neither worked. I ended up having to do this:
$constructor = $this->to_construct;
$myClass = new $constructor();
It seems like there should be a way to do this without storing the class name in a local variable. Am I missing something?
Have you tried this?
$myClass = new $this->to_construct;
Are you using PHP 4 or something? On 5.2.9 $myClass = new $this->to_construct(); works perfectly.
In the end it's what you have to live with, with PHP. PHP syntax and semantics are VERY inconsistent. For example, an array access to the result of a call is a syntax error:
function foo() {
return array("foo","bar");
}
echo $foo()[0];
Any other language could do that but PHP can't. Sometimes you simply need to store values into local variables.
Same is true for func_get_args() in older versions of PHP. If you wanted to pass it to a function, you needed to store it in a local var first.
If I read well between the lines you are trying to do something like this. Right?
class createObject{
function __construct($class){
$this->$class=new $class;
}
}
class B{
function __construct(){
echo 'class B constructed<br>';
}
function sayHi(){
echo 'Hi I am class: '.get_class();
}
}
class C{
function __construct(){
echo 'class C constructed<br>';
}
function sayHi(){
echo 'Hi I am class: '.get_class();
}
}
$wantedClass='B';
$finalObject = new createObject($wantedClass);
$finalObject->$wantedClass->sayHi();
--
Dam

Categories