开发者

php newbie question: classes

i'm new to php and am wondering - is it possible to initialize a class with parameters? like $obj = new myClass('myID');

i've tried but it gave me an err开发者_StackOverflow社区or.

maybe someone can point me to some good tutorials.

thanks


Yes it is, you need to pass the variables through the constructor:

class SomeClass
{
    function __construct($some_var)
    {
    }
}

Please note that in older versions of php the constructor needs to have the name of the class, it´s __construct() since php 5.


Yes, you need to use a class constructor.

Example:

<?php

class ClassWithArgs
{
  function __construct($argument1, $argument2)
  {
    echo "arg 1 = $argument1\n";
    echo "arg 2 = $argument2\n";
  }
}

$object = new ClassWithArgs('one', 'two');

?>

Example Output

arg 1 = one
arg 2 = two

I suggest you also take a look at the PHP5 OOP documentation, it includes simple examples to get you going: http://php.net/manual/en/language.oop5.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜